I’m using next-cookies
to store auth credentials from user session, however, I can’t get them during app initialization -let’s say, the user refreshes the page or comes back later-, however, after app has been initialized -or user has loged in-, I get them navigating in the app.
This is important, because I want to fetch some initial data to be available in to the redux store from the beginning.
// pages/_app.js
import { useStore } from '../store/store';
import nextCookie from 'next-cookies';
function MyApp({ Component, pageProps }) {
const Layout = Component.layout || MainLayout;
const store = useStore(pageProps.initialReduxState); // custom useStore method to init store
const pageTitle = Component.title || pageProps.title || 'Título de la página';
return (
<Provider store={store}>
<Layout pageTitle={pageTitle}>
<Component {...pageProps} />
</Layout>
</Provider>
);
}
export default MyApp;
MyApp.getInitialProps = async (ctx) => {
const { token, user } = nextCookie(ctx);
/* TO DO
the idea is to get cookie from the server side
and pass it to the client side, if the cookie is
active, initial data will be triggered from the
initializers
*/
return { pageProps: { token, user } };
};
Check it out:
Is it a better way or native option to get the cookie without having to a different cookie dependency?
Btw, I already have a middleware that protects routes from non authenticated user which works fine:
// pages/_middleware.js
export function middleware(req) {
const activeSession = req.headers.get('cookie');
const url = req.nextUrl.clone();
if (activeSession) {
if (req.nextUrl.pathname === '/login') {
url.pathname = '/';
return NextResponse.redirect(url);
}
return NextResponse.next();
}
url.pathname = '/login';
return NextResponse.rewrite(url);
}