question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

middleware NextResponse.rewrite combination with useRouter

See original GitHub issue

What 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:closed
  • Created 2 years ago
  • Comments:6 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
maaptehcommented, Dec 23, 2021

No Javi, let it stay closed forever 😃 Thanks for requesting the sample! Appreciated!

1reaction
balazsorban44commented, Dec 9, 2021

I’m not totally following what internal means here, a clear example would make it easier for me to answer.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Advanced Features: Middleware - Next.js
The NextResponse API allows you to: redirect the incoming request to a different URL; rewrite the response by displaying a given URL; Set...
Read more >
How to Use Next.js Middleware - ctnicholas.dev
Return a response​​ Copy code import type { NextRequest } from 'next/server' export function middleware (request: NextRequest) { return new ...
Read more >
Middleware in NextJS 12 - What are they and how to get ...
Middleware are simple pieces of code that allows one to modify the response to a request even before it is completed. We can...
Read more >
Supabase Auth with Next.js Server Components
Create a new file at /pages/middleware.js and populate with the following: ... function middleware(req) { const res = NextResponse.next() const supabase ...
Read more >
Rewrite HTML and transform page props in Next.js ... - YouTube
Next.js developers, do you wish you could do more with middleware ? What if instead of rewriting the URL of a page based...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found