Enable trust proxy on Next.js

Viewed 359

On Express.js, you do

// see https://expressjs.com/en/guide/behind-proxies.html
app.set('trust proxy', 1);

I am trying to add a ratelimit, and it's a Express middleware, which Next.js support, but I need to allow proxies on my Next.js app. I have tried googling but I haven't found anything helpful.

1 Answers

Express.js trust proxy sets the req.protocol to match the X-Forwarded-Proto header (see the source). As far as I know Next.js doesn't have a similar trust proxy setting. Also the middleware of the current (v12.2) Next.JS version doesn't allow the modification of the request object, so it's not possible to create a custom trust proxy middleware.

One solution is to create a wrapper around the Express middleware. This wrapper adds the protocol property to the request before passing it to Express middleware, and that added property should be sufficient for the ratelimit middleware to know it's behind a secure connection.

// middleware.js
import { NextResponse } from 'next/server';

export async function middleware(req) {
  const res = NextResponse.next();
  req.protocol = req.headers['x-forwarded-proto'] ?? 'http';
  await runExpressMiddleware(req, res, exampleMiddleware);
  return res;
}

function runExpressMiddleware(req, res, middlewareFn) {
  return new Promise((resolve, reject) => {
    middlewareFn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result);
      }
      return resolve(result);
    });
  });
}

function exampleMiddleware(req, res, next) {
  console.log(req.protocol); // Value of x-forwarded-proto header or http
  next();
}
Related