Skip to content

Instantly share code, notes, and snippets.

@nova4u
Created October 7, 2022 04:08
Show Gist options
  • Select an option

  • Save nova4u/d00f868f95d53206db6098e06d0ea976 to your computer and use it in GitHub Desktop.

Select an option

Save nova4u/d00f868f95d53206db6098e06d0ea976 to your computer and use it in GitHub Desktop.
Protect Client route with NextAuth
export const getServerSideProps = protectClientRoute(async () => {
return {
props: {},
};
});
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