Next.js force domain and or https (disallow serving site on ip or herokuapp.com)

Now that next.js does not recommend using a custom server, we have to find new ways of doing things. In express, we could simply use the following method to add middleware.


app.use(function(request, response, next) {
    if (process.env.NODE_ENV != 'development' && !request.secure) {
       return response.redirect("https://" + request.headers.host + request.url);
    }
    next();
})

However, if you are using next.js without a custom server and inbuilt API routes, you will need to add a middleware.ts file to the root of the project.

So if your pages directory is inside the src directory, then the middleware.ts file should be in the src directory.

Let's go ahead and create a middleware.ts file in the src directory. In this file, we will create a middleware function that will intercept all requests and redirect to the domain/hostname of your choice and also redirect to HTTPS if the request is not HTTPS.


import  { NextFetchEvent, NextRequest, NextResponse } from 'next/server'

type Environment = "production" | "development" | "other";
export function middleware(req: NextRequest, ev: NextFetchEvent) {
  if (process.env.NODE_ENV === 'production') {
    if (req.headers.get("x-forwarded-proto") !== "https" || !req.headers.get('host')?.includes('desired-domain.com')) {
        return NextResponse.redirect(
           `https://www.desired-domain.com${req.nextUrl.pathname}`,
           301
        );
    } 
    return NextResponse.next();
}