Skip to content

Instantly share code, notes, and snippets.

@htunnicliff
Created September 16, 2021 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htunnicliff/2b3b910b56070ae07e245446567613f3 to your computer and use it in GitHub Desktop.
Save htunnicliff/2b3b910b56070ae07e245446567613f3 to your computer and use it in GitHub Desktop.
Next.js Auth0 AuthGate Strategy
import AppProviders from "@/components/AppProviders";
import AppShell from "@/components/AppShell";
import { withAuth } from "@/lib/auth0/with-auth";
import { AppProps } from "next/app";
import { ReactNode } from "react";
interface MyAppProps extends AppProps {
err: Error;
Component: AppProps["Component"] & {
displayAppShell?: boolean;
requireAuth?: boolean;
};
}
function makeAuthGate({
children,
requireAuth,
}: {
children?: ReactNode;
requireAuth: boolean;
}) {
if (requireAuth) {
return withAuth(() => <>{children}</>);
} else {
return () => <>{children}</>;
}
}
function MyApp({ Component, pageProps, err }: MyAppProps) {
const displayAppShell = Component.displayAppShell ?? true;
const requireAuth = Component.requireAuth ?? true;
const AuthGate = makeAuthGate({
children: displayAppShell ? (
<AppShell>
<Component {...pageProps} err={err} />
</AppShell>
) : (
<Component {...pageProps} err={err} />
),
requireAuth,
});
return (
<AppProviders>
<AuthGate {...pageProps} />
</AppProviders>
);
}
export default MyApp;
import {
withPageAuthRequired,
WithPageAuthRequiredOptions,
WithPageAuthRequiredProps,
} from "@auth0/nextjs-auth0";
import { ComponentType } from "react";
export function withAuth(
Component: ComponentType<WithPageAuthRequiredProps>,
options: WithPageAuthRequiredOptions = {}
) {
return withPageAuthRequired(Component, {
onRedirecting: () => <p>Authenticating...</p>,
...options,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment