Skip to content

Commit ce256f2

Browse files
committed
fix: don't do permanent redirects in dev mode
`yarn dev:developer-docs` starts a nextJs devServer on localhost:3000/, which immediately yields a 301 - Permanent Redirect to localhost:3000/getting-started/ since Permanent Redirects get cached by the browser, all other projects that start a devserver on localhost:3000 will then redirect to /getting-started/, which likely doesn't exist. Since port 3000 is a popular port to be used in development, this permanent redirect can interfere with other projects, which is not a great DX. This fix changes redirects to HTTP Status Code 302 in development mode, which is a temporary redirect that doesn't get cached by browsers; in production, it's still fine to issue 301, as caching by the browser will make the redirect faster
1 parent 52fe1bc commit ce256f2

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/middleware.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,15 @@ export function middleware(request: NextRequest) {
2222
return handleRedirects(request);
2323
}
2424

25+
// don't send Permanent Redirects (301) in dev mode - it gets cached for "localhost" by the browser
26+
const redirectStatusCode = process.env.NODE_ENV === 'development' ? 302 : 301
27+
2528
const handleRedirects = (request: NextRequest) => {
2629
const urlPath = request.nextUrl.pathname;
2730

2831
const redirectTo = redirectMap.get(urlPath);
2932
if (redirectTo) {
30-
return NextResponse.redirect(new URL(redirectTo, request.url), {status: 301});
33+
return NextResponse.redirect(new URL(redirectTo, request.url), {status: redirectStatusCode});
3134
}
3235

3336
// If we don't find an exact match, we try to look for a :guide placeholder
@@ -50,7 +53,7 @@ const handleRedirects = (request: NextRequest) => {
5053
);
5154

5255
return NextResponse.redirect(new URL(finalRedirectToPath, request.url), {
53-
status: 301,
56+
status: redirectStatusCode,
5457
});
5558
}
5659

0 commit comments

Comments
 (0)