Endless Loop of Http Redirects in Node.js with Express

I need assistance with the code below which is meant to redirect all http traffic to https.

// Implement redirect logic to ensure usage of https in production, staging, and development environments
app.use((req, res, next) => {
  // Do not redirect to https if NODE_ENV is 'local', only for deployed server environments
  if(!['development', 'staging', 'production'].includes(process.env.NODE_ENV)) return next()

  if(!req.secure) {
    return res.redirect(301, `https://${req.headers.host}${req.originalUrl}`)
  }

  next()
})

/**
 * Initialize routes
 */
require('./routes')(app)

However, when testing it in the browser with a URL like http://example.com, I encounter a warning of a redirect loop and observe multiple console.log repetitions in my papertrail logs.

Is there something simple that I am overlooking? Any guidance would be greatly appreciated.

Answer №1

I recently stumbled upon this post on StackOverflow: In my experience with express.js, req.protocol doesn't recognize "https" for my secure link. It always defaults to "http"

By including the statement app.enable('trust proxy'), I was able to resolve the issue and run the aforementioned code successfully. This solution worked well for me as I am currently using Heroku.

Answer №2

Consider including a colon : after the protocol name in req.protocol === 'https:'.



// To ensure that HTTPS is always used in production, staging, and development environments
app.use((req, res, next) => {
  console.log('here')
  // Do not redirect to HTTPS if NODE_ENV is 'local', only for deployed server environments
  if(!['development', 'staging', 'production'].includes(process.env.NODE_ENV)) return next()

  // If request was made via HTTPS, proceed without any special handling
  if(req.protocol === 'https:') return next(); // <---- Remember to add : after https
  res.redirect('https://' + req.headers.host + req.url)
})

/**
 * Set up routes
 */
require('./routes')(app)

Update: The issue arises because the URL parser returns the protocol as https:. This can be observed from the examples in Node.js REPL mode.

$ node
> url.parse('https://ya.ru')
Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'ya.ru',
  port: null,
  hostname: 'ya.ru',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'https://ya.ru/'
}

The correct format for the protocol is https:, not just https as mentioned in the comments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ERROR: JSON parsing failed due to an unexpected token "<", indicating an issue with the syntax and structure of the input data

Currently, I am following a tutorial on Scrimba to learn about React and React Router 6. Unfortunately, I have encountered an error with the data provided in the tutorial. The error message reads as follows: 67:1 Uncaught (in promise) SyntaxError: Unexpect ...

"Enhance the appearance of bootstrap buttons by applying CSS to add shadow and border when the

Working on a frontend project using the React framework and Bootstrap 5.3 for design. Noticing that shadows are deactivated in Bootstrap by default, which means buttons don't display shadows when active as per the Bootstrap v5.0 documentation. Link ...

Access to the URL has been restricted by Google Storage

My MERN stack app utilizes Google Storage to store user profile pictures. However, I am encountering issues with accessing the storage when sending requests to the backend to retrieve the URL. {message: "Uploaded the file successfully: 9.png, but public a ...

Sending a picture through AJAX using the camera feature of p5.js

Currently, I am exploring the camera functionality of p5.js to capture video. However, I am facing a challenge when trying to upload these images to a server using ajax. I am unsure about how to convert a p5.js Image object into a suitable format for trans ...

Babel 6.x + Webpack 2 + React does not have compatibility with decorators

I have integrated transform-decorators-legacy into my project but I'm encountering the following error. The project is derived from react-redux-universal-hot-example but has been extended upon. I suspect the issue lies in either .babelrc or my webpack ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Getting the response from a Node.js fetch call and sending it directly to an Express response involves piping the

How can I forward the response from a nodejs fetch request to an express response? Is it possible to achieve this similar to how it was done with node-fetch modules? const fetchResponse = await fetch(myUrl); fetchResponse.body.pipe(expressResponse); ...

Why is applying CSS on an li element using .css() in JQuery not functioning?

Hey there! Could you please review my code? I'm attempting to add a top position to the <li> element using a variable in jQuery, but I'm not sure how to do it. Here's the code: <script> $(document).ready(function(){ ...

What is the purpose of setting the Z-Index on a Popper menu

If you want to see a live example demonstrating the issue, head over to codesandbox.io. My goal is to create a 'sit below' menu just like it's shown in the Material-UI documentation here. return ( <div className={classes.root}&g ...

Having trouble establishing a connection between Node.js and Azure MySQL

Today, I encountered an issue while attempting to connect and retrieve data from Azure Database for MySQL using nodejs. I'm currently testing the connection, but it seems to not be working. Note: The database does exist Example: const db = mysql.cre ...

Select a random object from a document and dispatch it. A Discord bot

I'm looking to enhance my bot by adding a command that retrieves a random quote from a JSON file and displays it in chat. I've already figured out how to do this using an array, but I'm not sure how to pull the quotes from a file. EDIT: ...

Setting AWS SES TemplateData dynamically with Node.js: a step-by-step guide

I am attempting to send a custom data email. async function sendCustomEmailToSalesTeam(email, name, phoneNumber, utmSource, utmTerm, utmMedium, deviceType, browser, referrer) { try { let emailMe = "<a href="/cdn-cgi/l/email-protection" clas ...

The functionality does not seem to be functioning in Mozilla Firefox, however it is working correctly in Chrome when the following code is executed: `$('input[data-type="choise"

I am currently working on an online test portal and everything is functioning properly with Chrome. However, I am encountering an issue with Mozilla Firefox. My code works fine in Chrome but not in Mozilla Firefox. Please suggest an alternative solution to ...

Unable to use the unlink function when using a relative path

In my website backend, I am using the express framework. There is an express public folder where user-uploaded images are stored in an upload folder within the public directory. Additionally, there is a routes folder outside the public directory where I cr ...

Difficulty switching back and forth between three varying heights

I have a container with a button labeled "Show more". Upon clicking the button, the height of the container will transition through 3 different states. <div class="segment-suggestion-content height-small"> <div class="segment-suggestion-sh ...

Encountering an issue when utilizing a personalized directive with AngularJS

I'm encountering an issue with the "auto-complete" directive that I'm using from jsfiddle. The error message I'm receiving is iElement.autocomplete is not a function. Can someone help me troubleshoot and fix this error? directive.js starte ...

What is the recommended default value for a file in useState when working with React and TypeScript?

Can anyone help me with initializing a file using useState in React Typescript? const [images, setImages] = useState<File>(); const [formData, setFormData] = useState({ image: File }); I'm facing an issue where the file is sho ...

Attempting to achieve a carousel animation using jQuery

Upon loading the page, only one character out of four is displayed. Two arrows are provided - one on the left and one on the right. Clicking on the left arrow causes the current character to fade out and the previous character to fade in. Clicking on the r ...

Vuetify - Implementing a search feature in a table that automatically navigates to the matching row

Currently, I am working with 2 Vuetify data tables that do not have pagination enabled. Each row in the second table corresponds to exactly one parent in the first table. My goal is to be able to click on an entry in the second table and have it automati ...

Troubleshooting the ERR_CONNECTION_RESET issue when uploading large files on Angular 7 with Node JS and IIS, using pm2 for

Can you assist me? I am encountering a problem where the connection gets reset and an error message ERR_CONNECTION_RESET appears when trying to upload large files (150+MB) to the server. This issue only occurs when interacting with the public API, everythi ...