middleware NextResponse.rewrite combination with useRouter
See original GitHub issueWhat version of Next.js are you using?
12.0.7
What version of Node.js are you using?
16.7.0
What browser are you using?
Chrome
What operating system are you using?
macOS
How are you deploying your application?
next start
Describe the Bug
When using the middleware we use the ‘NextResponse.rewrite’ option to move traffic to other internal places (by doing so we can keep our SEO requirements in place) on route change when passing just a simple query param it wants to go further on the internal part.
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const hostname = req.headers.get('host');
const country = getCountryCode(hostname);
if (pathname.startsWith('/locales')) {
return new Response(null, { status: 404 });
}
// when we are on NL website use nl internally
if (
country === 'nl' &&
!pathname.includes('.') && // exclude all files in the public folder
!pathname.startsWith('/api') // exclude all API routes
) {
if (pathname.startsWith('/nl')) {
return new Response(null, { status: 404 });
}
return NextResponse.rewrite(`/locales/nl-NL${pathname}`);
}
}
My browser url clearly shows: ‘http://mpth.nl:3001/tafels-en-bureaus/bijzettafels’
Then the pathname of ‘NextRouter’ shows it is “/locales/nl-NL/tafels-en-bureaus”, which it isn’t (maybe internal, but certainly not when looking from client url perspective).
Now when I do a client-side call for the next page (updating a query parameter) it then also wants to go to the “internal” endpoint by apending “/locales/nl-NL” to the route.
Is it possible to get both pathnames 😃 ?
Expected Behavior
I hoped the internal folder structure with a rewrite would not be pushed to the client code. It seems to be now! All absolute urls using next Link work fine. But i also expect that for the useRouter
export { useRouter } from 'next/router';
it seems pathname is the internal one (totally understandable), but i would like to also have the public one (client).
Now im using an altered pathname:
router.push({
pathname: window.location.pathname,
query: params,
});
To bypass the issue
To Reproduce
If needed i can make an example, i firstly hope maybe by adding my used middleware its clear 😃
https://codesandbox.io/s/github/maapteh/i18n-internal/tree/main
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (6 by maintainers)
Top GitHub Comments
No Javi, let it stay closed forever 😃 Thanks for requesting the sample! Appreciated!
I’m not totally following what internal means here, a clear example would make it easier for me to answer.