Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FatehAK/32fe88b2743a262aad0967dc506a78cb to your computer and use it in GitHub Desktop.
Save FatehAK/32fe88b2743a262aad0967dc506a78cb to your computer and use it in GitHub Desktop.
HTTP to HTTPS redirect with NextJs Heroku

To configure an HTTP -> HTTPS redirect using NextJs on Heroku, is necessary to configure a NextJs custom server.

Here is a custom server configured with the redirect working:

server.js

const express = require('express');
const cookieParser = require("cookie-parser");
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const sslRedirect = (environments = ["production"], status = 302) => {
  const currentEnv = process.env.NODE_ENV;
  const isCurrentEnv = environments.includes(currentEnv);
  return (req, res, next) => {
      if (isCurrentEnv && req.headers["x-forwarded-proto"] !== "https") {
        res.redirect(status, "https://" + req.hostname + req.originalUrl)
      }
      else {
        next();
      }
  };
};

app
  .prepare()
  .then(() => {

    const server = express();
    server.use(express.json());
    server.use(express.urlencoded({ extended: true }));
    server.use(cookieParser());

    server.use(sslRedirect());

    server.get('*', (req, res) => handle(req, res));
    
    server.post('/api/auth/*', (req, res) => handle(req, res));

    server.listen(
      port,
      error => {
        if (error) throw error;
        console.log(`Listening on port ${port}`);
      }
    );

  })
  .catch(error => {
    console.error(error);
    process.exit(1);
  });

Also, you need to edit your package.json to use the ser server config:

Change the start script to run the server.

package.json

"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "NODE_ENV=production node server.js",
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment