@auth0/nextjs-auth0
Version:
Auth0 Next.js SDK
38 lines (37 loc) • 1.32 kB
JavaScript
export const appRouteHandlerFactory = (client, config) => (handler, opts = {}) => async (params) => {
const session = await client.getSession();
if (!session?.user) {
const returnTo = typeof opts.returnTo === "function"
? await opts.returnTo(params)
: opts.returnTo;
const { redirect } = await import("next/navigation.js");
redirect(`${config.loginUrl}${opts.returnTo ? `?returnTo=${returnTo}` : ""}`);
}
return handler(params);
};
export const pageRouteHandlerFactory = (client, config) => ({ getServerSideProps, returnTo } = {}) => async (ctx) => {
const session = await client.getSession(ctx.req);
if (!session?.user) {
return {
redirect: {
destination: `${config.loginUrl}?returnTo=${encodeURIComponent(returnTo || ctx.resolvedUrl)}`,
permanent: false
}
};
}
let ret = { props: {} };
if (getServerSideProps) {
ret = await getServerSideProps(ctx);
}
if (ret.props instanceof Promise) {
const props = await ret.props;
return {
...ret,
props: {
user: session.user,
...props
}
};
}
return { ...ret, props: { user: session.user, ...ret.props } };
};