Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: don't do permanent redirects in dev mode #12533

Merged
merged 2 commits into from
Feb 3, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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
TkDodo committed Jan 31, 2025
commit ce256f23cd555c05670a78b0b1c6bdb25a27d6f5
7 changes: 5 additions & 2 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -22,12 +22,15 @@ export function middleware(request: NextRequest) {
return handleRedirects(request);
}

// don't send Permanent Redirects (301) in dev mode - it gets cached for "localhost" by the browser
const redirectStatusCode = process.env.NODE_ENV === 'development' ? 302 : 301

const handleRedirects = (request: NextRequest) => {
const urlPath = request.nextUrl.pathname;

const redirectTo = redirectMap.get(urlPath);
if (redirectTo) {
return NextResponse.redirect(new URL(redirectTo, request.url), {status: 301});
return NextResponse.redirect(new URL(redirectTo, request.url), {status: redirectStatusCode});
}

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

return NextResponse.redirect(new URL(finalRedirectToPath, request.url), {
status: 301,
status: redirectStatusCode,
});
}