Created
October 7, 2022 04:08
-
-
Save nova4u/d00f868f95d53206db6098e06d0ea976 to your computer and use it in GitHub Desktop.
Protect Client route with NextAuth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const getServerSideProps = protectClientRoute(async () => { | |
| return { | |
| props: {}, | |
| }; | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { authOptions } from "@src/pages/api/auth/[...nextauth]"; | |
| import { GetServerSidePropsContext } from "next"; | |
| import { unstable_getServerSession } from "next-auth"; | |
| const protectClientRoute = (callback: (context: GetServerSidePropsContext) => void, redirect: string | undefined = "/") => { | |
| return async (context: GetServerSidePropsContext) => { | |
| const session = await unstable_getServerSession(context.req, context.res, authOptions); | |
| if (!session) | |
| return { | |
| redirect: { | |
| destination: redirect, | |
| permanent: false, | |
| }, | |
| }; | |
| return callback(context); | |
| }; | |
| }; | |
| export default protectClientRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment