0

I'm building a simple client app with react and next-auth.
I want to protect only one route /secret and the rest of routes are all publicly accessible.

The top level of app is wrapped with SessionProvider:

    import { SessionProvider } from "next-auth/react"
    export default function MyApp({
      Component,
      pageProps: { session, ...pageProps },
    }) {
      return (
        <SessionProvider session={session}>
          <Component {...pageProps} />
        </SessionProvider>
      )
    }

And I understood I can use useSession to check if user is signed in.
But I wonder how to protect one specific route: /secret. If I wrap only <Secret /> component with <SessionProvider>, I won't be able to access session from Secret component. Then how can I do that..?

zhulien
  • 5,145
  • 3
  • 22
  • 36
doobean
  • 1,929
  • 4
  • 19
  • 27

1 Answers1

2

You can use NextAuth's middleware, create a middleware.js file in your root directory (on previous Next.js versions, you had to create a _middleware.js file inside your pages folder) and add this:

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

export const config = { matcher: ["/your-secured-route"] }

If you don't add a config, then all routes will be protected by default.

ivanatias
  • 3,105
  • 2
  • 14
  • 25
  • I tried this, but adding a middleware.ts does not do anything to my app. How come? – m3.b Mar 16 '23 at 18:57
  • What Next.js and Next auth versions are you using? – ivanatias Mar 19 '23 at 18:58
  • I made it work (directory issue), but actually, just with this code in it, my middleware will make me stuck on the login page, even after successful login. Next is on latest, and next-auth is 4.20.1+ – m3.b Mar 20 '23 at 17:42