Search code examples
next.jsnext-auth

Next-auth - Middleware has no protective effect on my app, I don't know hwy?


I followed the basic setup of next-auth to use in my app, using the Credentials provider.

I have correctly applied the SessionProvider to my _app.tsx

Next, the way I understood to protect your app easily, would be to simply add a middleware.ts to your source folder (same folder as the pages/ folder , with the following.

export { default } from "next-auth/middleware";

export const config = { matcher: ["/dashboard"] };

How is that that, if I start my program, and go straight to http://localhost:3000/dashboard, the page shows properly? even though the logs show the session.status unauthenticated? I would expect it to be blocked.

I have not managed in the /dashboard page the condition that if sesssion.status is unauthorized case. But I would have imagined that the middleware would have taken care of this? Or what's the purpose? What should I expect?


Solution

  • you have to add NEXTAUTH_SECRET to your .env file :

    NEXTAUTH_SECRET=EXAMPLESECRET
    

    also make sure

    1. you sign out before testing it because if you rebuild your app that does not sign out the user
    2. the middleware file you use had the correct name middleware .ts/.js
    3. the path you've set in the matcher array is the same as the path you want to apply the middleware to.
    4. the middleware file is in the source folder