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..?
CodePudding user response:
You can keep the SessionProvider
in MyApp
and check for the session in getServerSideProps
inside the Secret
page:
import { getSession } from 'next-auth/react';
export const getServerSideProps = async (context) => {
const session = await getSession(context);
if (!session) {
// Unauthorized, redirect to public route
return { redirect: { destination: `/`, permanent: false } };
}
return { props: { } }
};
CodePudding user response:
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.