how to trigger nextjs middleware on next/link

Viewed 419

Hi i'm currently using nextjs middleware to check authentication for every page

everything works fine when I'm navigating from the browser URL.

But when I try to navigate using next/link. it's skipped the middleware check. I think this is by design on how next/link works because of the prefetch thing.

Is there a workaround that we can use to trigger nextjs middleware manually with next/link ?

import Link from 'next/link'

<Link href="/admin">Admin</Link>
2 Answers

I think it does not skip checking, in reality it is already done when you prefetch, If you want to check authentication/authorization please use

 <Link prefetch={false} />

(in my opinion, I see powerful in nextjs middleware and I would like to use the same as you but we used it we can't use the prefetch feature because there has a lot of bugs that I found.

add this to your response

response.headers.set(`x-middleware-cache`, `no-cache`);
Related