Last active
February 23, 2022 15:37
-
-
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.).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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