1

I am new on Next.js. Before I use react. For that I use react context api for user authentication store. But it give me problem when redirect pages. For this I try use getInitialProps on _app.js file:

import React, { useState, useEffect } from 'react';
import '../styles/globals.css';
import { appWithTranslation } from 'next-i18next';
import { ThemeProvider } from 'next-themes';
import nprogress from 'nprogress';
import { useRouter } from 'next/router';
import App from 'next/app';
import axios from 'axios';
import { Footer, Navbar } from '../components';
import '../styles/nprogress.css';
import { AuthProvider } from '../context/authContext';

const MyApp = ({ Component, pageProps, noProtected }) => {
  const [mounted, setMounted] = useState(false);

  const routerM = useRouter();

  useEffect(() => {
    setMounted(true);
    routerM.events.on('routeChangeStart', () => nprogress.start());
    routerM.events.on('routeChangeComplete', () => nprogress.done());
    routerM.events.on('routeChangeError', () => nprogress.done());
  }, []);

  if (!mounted) return null;
  return (
    <ThemeProvider attribute="class">
      <AuthProvider>

        <Navbar />
        <div className="pt-65">
          <Component {...pageProps} noProtected={noProtected} />
        </div>
        <Footer />

      </AuthProvider>

    </ThemeProvider>
  );
};

MyApp.getInitialProps = async (appContext) => {
  const appProps = await App.getInitialProps(appContext);
  const { ctx } = appContext;
  const noProted = ctx.pathname === '/login'
    || ctx.pathname === '/register'
    || ctx.pathname === '/forgot'
    || ctx.pathname === '/activate/[id]/[token]'
    || ctx.pathname === '/confirm_password/[email]/[token]';

  await axios.get(`${process.env.SERVER}/users/auth`, { withCredentials: true })
    .then((res) => {
      const { data } = res;
      console.log('data:', data);
    })
    .catch((err) => {
      console.log('err');
    });

  return { ...appProps, noProtected: noProted };
};

export default appWithTranslation(MyApp);

When I use this function on AuthContext work well. After login every refresh page show me current user but inside getInitialProps dont work:

await axios.get(`${process.env.SERVER}/users/auth`, { withCredentials: true })
        .then((res) => {
          const { data } = res;
          console.log('data:', data);
        })
        .catch((err) => {
          console.log('err');
        });

Is someone have any idea? I cannot sole this. I try send cookie to backend server. On backend I use passport.js and express-session for this I send connect.sid cookie. But it dont help me

  • That's most likely because, unlike requests made from the client-side, requests in `getInitialProps` are made from the server (on initial page load), meaning you have to to explicitly pass the cookies to the axios request to send them through. See [Why are cookies not sent to the server via getServerSideProps in Next.js?](https://stackoverflow.com/q/69057271/1870780). – juliomalves Oct 10 '22 at 22:45

0 Answers0