Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Last active February 23, 2022 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanmaslyn/c70f5a59a67fb0f0705f2ffd23acc576 to your computer and use it in GitHub Desktop.
Save jordanmaslyn/c70f5a59a67fb0f0705f2ffd23acc576 to your computer and use it in GitHub Desktop.
Use Next.js Middleware to standardize around one domain (e.g. force www, redirect from a platform subdomain to custom domain, etc.).
import { NextRequest, NextResponse } from "next/server";
export function middleware(req: NextRequest) {
// PRIMARY_DOMAIN should be a full URL including protocol, e.g. https://www.google.com
const hasEnvVariable = !!process.env.PRIMARY_DOMAIN;
const isDevelopment = process.env.NODE_ENV === "development";
if (!hasEnvVariable) {
!isDevelopment &&
console.error(
"You must provide a PRIMARY_DOMAIN environment variable for the domain normalization middleware to work correctly"
);
return NextResponse.next();
}
const url = req.nextUrl.clone();
const normalizedHost = new URL(process.env.PRIMARY_DOMAIN);
const host = req.headers.get("host");
const isCorrectHostname = host.split(":")[0] === normalizedHost.hostname;
if (!isCorrectHostname) {
url.protocol = normalizedHost.protocol;
url.host = normalizedHost.host;
url.port = normalizedHost.port;
return NextResponse.redirect(url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment