Next.js 15 + Kinde Auth – Protected routes not working after logout
Hey, I’m new to Next.js and I’m having the following issue:
I integrated Kinde login into my app, and login itself works fine. Afterwards, I want my routes to be protected – meaning that after logout I shouldn’t be able to access my pages/routes anymore unless I’m logged in.
The problem:
Even after logging out, I can still access my other pages – which should not be possible.
I followed a tutorial where the solution was to create a middleware.js in the lib folder with the following code:
3 Replies
Hi, Thanks for reaching out
The issue is just how the middleware is set up. What’s going wrong -
Let me know if this helps, Thanks
The issue is just how the middleware is set up. What’s going wrong -
middleware.ts/js must live at the project root, not in lib/. If it’s inside lib/, Next.js never runs it, so your routes aren’t actually protected after logout.
- Also, use the documented withAuth pattern (callback + options), not withAuth(req, options).
To Fix: Create /middleware.ts at the project root (same level as app/ or pages/)
This is exactly how Kinde recommends protecting all routes (except Next internals and static files).
- Use the built-in auth routes (if you haven’t already):
- Use Kinde’s <LogoutLink /> or hit /api/auth/logout, and set KINDE_POST_LOGOUT_REDIRECT_URL to a public page (e.g., your homepage).
After you move it
- Restart the dev server so Next picks up the new middleware.
- Test in an incognito window:
1. Visit a protected route → you should be redirected to login
2. Log in → you land on the intended page
3. Log out → visiting the protected route again should redirect to login
If you want some pages to stay public while logged out, add them to publicPaths as shown above.Let me know if this helps, Thanks
Hi, thank you so much for your long and detailed response!
You’ve solved my problem — the issue was that I had placed the middleware inside the lib/ folder. (Strangely enough, in the tutorial it was also placed in lib/ and worked there, which confused me a bit.)
I really appreciate that you took the time to help me out ❤️
Glad it worked, Thanks
Let us know if you have any other question. Thanks
Let us know if you have any other question. Thanks