Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Can't get cookie during _app initialization with getInitialProps

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:

enter image description here

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);
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!