Created
September 16, 2021 21:15
-
-
Save htunnicliff/2b3b910b56070ae07e245446567613f3 to your computer and use it in GitHub Desktop.
Next.js Auth0 AuthGate Strategy
This file contains 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 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; |
This file contains 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 { | |
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