Protecting routes in Next.js App Router middleware
Docs at https://kinde.com/docs/developer-tools/nextjs-sdk/#protect-routes-using-middleware mention:
As of right now the middleware in the app router does not work when trying to redirect to api/auth/login. This is because of Next.js caching which causes issues during authentication.Should I read this as "currently, protecting routes in the middleware doesn't work, and the code examples mentioned in this docs section won't work either"? When the user is signed out, and I navigate to http://localhost:3000, I can see that the middleware is hit with the
api/auth/login
pathname.
So, I'm trying to understand what exactly is not working in the middleware.
On another note, withAuth()
doesn't seem to be properly typed. Any plans to have proper types so that we could see for example what type publicPaths
is in the middleware options? I could probably guess that it's an array of strings, but no idea for example if regex is supported. Having some examples in the docs would also help πKinde Docs
NextJS App Router SDK - Developer tools - Help center
Our developer tools provide everything you need to get started with Kinde.
8 Replies
Hey Misha. Checking if this is blocking you? Or if this is mainly suggestions for improving docs? Just so I know what I need to do next.
Yes, blocking, as I don't understand what to expect from the middleware. As mentioned above, I'm confused about this:
middleware in the app router does not work when trying to redirect to api/auth/loginImproving the TypeScript types on the other hand is a nice to have (not blocking).
Okay thanks. Will see if I can get an eng to answer on this.
The docs are out of date! We will update it with more info about the middleware
At the moment you can use the middleware like this:
I'd like to understand how to do custom redirect rules in the middleware based on user permissions and requested url.
Is it possible at the moment?
Since the middleware runs in the Edge runtime, I wonder if I can just
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
and get the user from the server session? Does @kinde-oss/kinde-auth-nextjs/server
support the Edge runtime or only Node?Should be able to use getKindeServerSession in middleware
custom redirect rules can be done like this:
https://kinde.com/docs/developer-tools/nextjs-sdk/#protecting-routes
Kinde Docs
NextJS App Router SDK - Developer tools - Help center
Our developer tools provide everything you need to get started with Kinde.
How would I do a redirect with this approach? e.g. if the user has a certain claim I want to redirect to
/foo
?