Search code examples
reactjsnext.jsnext-auth

How to protect specific route in next-auth


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..?


Solution

  • 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.