I wan't for all pages if I has not token then redirect to /login
in _app,js file I added
export const getServerSideProps = async () => {
return {
props: {},
redirect: { destination: "/login" },
};
}
Then I run npm run build and start but getServerSideProps redirect dont wok for any pages
Maybe I created incorrect build not in prod mode ?
CodePudding user response:
Unfortunately, getServerSideProps
is not supported in _app
file right now. You can check this document for the reference.
But we can achieve the same thing with getInitialProps
App.getInitialProps = (ctx) => {
//TODO: Check authenticated value in cookies or somewhere in your code
const isAuthenticated = false
if(!isAuthenticated) {
if(typeof window === 'undefined'){ //server-side rendering
res.redirect('/login')
res.end()
return {}
} else { //client-side rendering
Router.push('/login')
return {}
}
}
return {
props: {}
}
}
Following this document again
Adding a custom getInitialProps in your App will disable Automatic Static Optimization in pages without Static Generation.
You need to consider this trade-off too.
If you want to handle it without these side effects. I'd suggest you use Context API
. Your _app.js
may be like this
const App = ({ Component, pageProps }) => {
return <AuthenticationProvider>
<Component {...pageProps}/>
</AuthenticationProvider>
}
After that, you can do some redirection stuff inside AuthenticationProvider
that will apply to all pages
CodePudding user response:
you don't need to use this for hard coding the "/login" you can easily write it in your component, the point of the getServerSideProps function is to fetch data from the backend and preload the data