Since you're wanting to create protected routes with a static export, you'll need to do everything in the browser.
- Verify their JWT in the browser
- If their JWT is valid, render the page (including all requests to fetch data)
- If their JWT is not valid, redirect them
For this, we're going to create a wrapper AuthCheck
component.
Related:
How can you create a Private route in next.js?
AuthCheck
For verifying the JWT, you can use any method you'd like, including sending it to an api endpoint to verify it. Though I'm unsure if you can use Next.js api endpoints with static exports.
import { useRouter } from 'next/router'
export const AuthCheck = (props) => {
const router = useRouter()
const isJWTValid = useIsJWTValid() // you need to implement this. In this example, undefined means things are still loading, null means user is not signed in, anything truthy means they're signed in
if (typeof window !== 'undefined' && user === null) router.push('/')
if(!user) return <Loading /> // a loading component that prevents the page from rendering
return props.children
}
You can then add this to your app.js.
const MyApp = ({ Component, pageProps }) => {
return (
<AuthCheck>
<Component {...pageProps} />
</AuthCheck>
)
}
export default MyApp
Alternatively, you can also add this to any individual page. With this, you may need to debug the timing of any fetched data.
export default const ProtectedPage = () => {
return (
<AuthCheck>
<!-- contents of the page -->
</AuthCheck>
)
}