Home > database >  Nextjs next-auth sessionProvider not reading session property Typescript
Nextjs next-auth sessionProvider not reading session property Typescript

Time:09-11

I am using the mantine template with Next-auth and I try to implement the sessionProvider in the application, I get the error session is not defined

Error implementing session on session provider

----Edit---- code of the error using just session on sessionProvider

error - pages\_app.tsx (33:38) @ App
error - ReferenceError: session is not defined
    at App (webpack-internal:///./pages/_app.tsx:85:38)
    at renderWithHooks (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5658:16)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5731:15)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5785:7)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14) {
  page: '/protegido'
}
  31 |         <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
  32 |           <NotificationsProvider>
> 33 |             <SessionProvider session={session}>
     |                                      ^
  34 |               <ApolloProvider client={client}>
  35 |                 <Component {...pageProps} />
  36 |               </ApolloProvider>

I'm importing it in my _app.tsx like so

import { GetServerSidePropsContext } from 'next';
import { useState } from 'react';
import { AppProps } from 'next/app';
import { getCookie, setCookie } from 'cookies-next';
import Head from 'next/head';
import { MantineProvider, ColorScheme, ColorSchemeProvider } from '@mantine/core';
import { NotificationsProvider } from '@mantine/notifications';
import { SessionProvider } from 'next-auth/react';
import { ApolloProvider } from '@apollo/client';
import client from '../apollo-client';

export default function App(props: AppProps & { colorScheme: ColorScheme }) {
  const { Component, pageProps } = props;
  const [colorScheme, setColorScheme] = useState<ColorScheme>(props.colorScheme);

  const toggleColorScheme = (value?: ColorScheme) => {
    const nextColorScheme = value || (colorScheme === 'dark' ? 'light' : 'dark');
    setColorScheme(nextColorScheme);
    setCookie('mantine-color-scheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 });
  };

  return (
    <>
      <Head>
        <title>Family 5 Dashboard</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
        <link rel="shortcut icon" href="/icono.png" />
      </Head>

      <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>
        <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
          <NotificationsProvider>
            <SessionProvider session={session}>
              <ApolloProvider client={client}>
                <Component {...pageProps} />
              </ApolloProvider>
            </SessionProvider>
          </NotificationsProvider>
        </MantineProvider>
      </ColorSchemeProvider>
    </>
  );
}

App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  colorScheme: getCookie('mantine-color-scheme', ctx) || 'dark',
});

I get the same error if I use pageProps.session

session provider error

----Edit---- code of the error using just pageProps.session on sessionProvider

error - pages\_app.tsx (33:48) @ App
error - TypeError: Cannot read properties of undefined (reading 'session')
    at App (webpack-internal:///./pages/_app.tsx:85:48)
    at renderWithHooks (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5658:16)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5731:15)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5785:7)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14) {
  page: '/protegido'
}
  31 |         <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
  32 |           <NotificationsProvider>
> 33 |             <SessionProvider session={pageProps.session}>
     |                                                ^
  34 |               <ApolloProvider client={client}>
  35 |                 <Component {...pageProps} />
  36 |               </ApolloProvider>

---edit now with [...nextauth] file-----

my /api/auth/[...nextauth].js

import NextAuth from "next-auth"
import { ApolloClient, InMemoryCache } from "@apollo/client";
import CredentialsProvider from "next-auth/providers/credentials";
import { GET_ADMIN_LOGIN } from "../../../components/fam.querys";

export default NextAuth({

    providers: [
        CredentialsProvider({
            session: {
                strategy: 'jwt',
                maxAge: 30 * 24 * 60 * 60, //30 days
                updateAge: 24 * 60 * 60, // 24 hours
            },
            // The name to display on the sign in form (e.g. "Sign in with...")
            name: "Credentials",
            // e.g. domain, username, password, 2FA token, etc.
            credentials: {
                email: { label: "email", type: "email", placeholder: "correo" },
                password: { label: "Password", type: "password", placeholder: 'clave' }
            },
            async authorize(credentials, req) {
                // Add logic here to look up the user from the credentials supplied

                const client = new ApolloClient({
                    uri: "myUri",
                    cache: new InMemoryCache(),
                    headers: {
                        'content-type': 'application/json',
                        'x-hasura-admin-secret': '*******'
                    }
                })

                //buscar en la base de datos si existe el usuario

                /* try {
                    await client.resetStore();
                    const { data } = await client.query({
                        query: GET_ADMIN_LOGIN,
                    });

                    const adminPass = data?.control_admin[0]?.clave
                    const adminId = data?.control_admin[0]?.id
                    const adminCorr = data?.control_admin[0]?.correoadmin
                    const adminName = data?.control_admin[0]?.correoadmin

                    if (credentials.email === adminCorr && credentials.password === adminPass) {
                        return {
                            user: {
                                id: 311,
                                image: adminId,
                                name: adminName,
                                email: adminCorr,
                                tipo: 'admin'
                            },
                        }
                    }
                    return null;
                } catch (error) {
                    console.log(error)
                } */

                if (credentials.email !== '[email protected]' || credentials.password !== '1234') {
                    return null;
                }
                // si todo esta bien
                return { id: '1234', name: 'john', email: '[email protected]', tipo: 'extra' };
            }
        })
    ],

    callbacks: {
        session: async ({ session, token }) => {
            if (session?.user) {
                session.user.id = token.uid;
                session.user.tipo = token.tipo;
            }
            console.log('sesion: ', session)

            return session;
        },
        jwt: async ({ user, token }) => {
            if (user) {
                token.uid = user.id;
                token.tipo = user.tipo;
            }
            console.log('token: ', token)
            console.log('user: ', user)
            return token;
        },
    },
    pages: {
        signIn: '/',
    },
});

following Yilmaz suggestion I made a ts file like so

import {
  Session
} from 'next-auth';
import {
  JWT
} from 'next-auth/jwt';

declare module 'next-auth' {
  interface Session {
    // what ever properties added, add type here
    expires: string;
    user: {
      email: string;
      id: number;
      name: string;
      tipo: string;
    };
  }
}

then tried again on the _app file

import { GetServerSidePropsContext } from 'next';
import { useState } from 'react';
import { AppProps } from 'next/app';
import { getCookie, setCookie } from 'cookies-next';
import Head from 'next/head';
import { MantineProvider, ColorScheme, ColorSchemeProvider } from '@mantine/core';
import { NotificationsProvider } from '@mantine/notifications';
import { SessionProvider } from 'next-auth/react';
import { ApolloProvider } from '@apollo/client';
import client from '../apollo-client';
import { Session } from 'next-auth';

export default function App(props: AppProps & { colorScheme: ColorScheme }) {
  const { Component, pageProps } = props;
  const [colorScheme, setColorScheme] = useState<ColorScheme>(props.colorScheme);

  const toggleColorScheme = (value?: ColorScheme) => {
    const nextColorScheme = value || (colorScheme === 'dark' ? 'light' : 'dark');
    setColorScheme(nextColorScheme);
    setCookie('mantine-color-scheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 });
  };

  return (
    <>
      <Head>
        <title>Family 5 Dashboard</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
        <link rel="shortcut icon" href="/icono.png" />
      </Head>

      <SessionProvider session={pageProps.session}>
        <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>
          <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
            <NotificationsProvider>
              <ApolloProvider client={client}>
                <Component {...pageProps} />
              </ApolloProvider>
            </NotificationsProvider>
          </MantineProvider>
        </ColorSchemeProvider>
      </SessionProvider>
    </>
  );
}

App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  colorScheme: getCookie('mantine-color-scheme', ctx) || 'dark',
});

I still get this error

TypeError: Cannot read properties of undefined (reading 'session')
    at App (webpack-internal:///./pages/_app.tsx:75:36)
    at renderWithHooks (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5658:16)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5731:15)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5785:7)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
wait  - compiling /_error (client and server)...
event - compiled client and server successfully in 853 ms (1092 modules)
error - pages\_app.tsx (31:42) @ App
error - TypeError: Cannot read properties of undefined (reading 'session')
    at App (webpack-internal:///./pages/_app.tsx:75:36)
    at renderWithHooks (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5658:16)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5731:15)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5785:7)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14) {
  page: '/'
}
  29 |       </Head>
  30 | 
> 31 |       <SessionProvider session={pageProps.session}>
     |                                          ^
  32 |         <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>   
  33 |           <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
  34 |             <NotificationsProvider>

if I use <SessionProvider session={props.session}>

I don't get any error, but does not maintain the session or the user object, if u reload the page or change tabs the session is lost

after making the next.d.ts

and using <SessionProvider session={pageProps.session}>

the error that came out is:

TypeError: Cannot read properties of undefined (reading 'session')
    at App (webpack-internal:///./pages/_app.tsx:75:36)
    at renderWithHooks (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5658:16)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5731:15)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-d om-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5785:7)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
wait  - compiling /_error (client and server)...
event - compiled client and server successfully in 961 ms (1041 modules)
error - pages\_app.tsx (31:42) @ App
error - TypeError: Cannot read properties of undefined (reading 'session')
    at App (webpack-internal:///./pages/_app.tsx:75:36)
    at renderWithHooks (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5658:16)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5731:15)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14)
    at renderIndeterminateComponent (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5785:7)
    at renderElement (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:5946:7)
    at renderNodeDestructiveImpl (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6104:11)
    at renderNodeDestructive (C:\Users\alfon\Documents\GitHub\Matrix_Family\node_modules\react-dom\cjs\react-dom-server.browser.development.js:6076:14) {
  page: '/'
}
  29 |       </Head>
  30 | 
> 31 |       <SessionProvider session={pageProps.session}>
     |                                          ^
  32 |         <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>  
  33 |           <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
  34 |             <NotificationsProvider>

CodePudding user response:

create next-auth.d.ts in file at the root directory and add this:

import { Session } from "next-auth"
import { JWT } from "next-auth/jwt"

declare module "next-auth" {
  interface Session {
    // what ever properties added, add type here
    user: User
  }
}

Also at root directory, create next.d.ts and add this. from docs:

import type { NextComponentType, NextPageContext } from "next"
import type { Session } from "next-auth"
import type { Router } from "next/router"

declare module "next/app" {
  type AppProps<P = Record<string, unknown>> = {
    Component: NextComponentType<NextPageContext, any, P>
    router: Router
    __N_SSG?: boolean
    __N_SSP?: boolean
    pageProps: P & {
      /** Initial session passed in from `getServerSideProps` or `getInitialProps` */
      session?: Session
    }
  }
}

this is normal ts set up for this _app.tsx

 export default function App({ Component, pageProps }: AppProps) {

But since you defined your component like this

export default function App(props: AppProps & { colorScheme: ColorScheme }) {

we have to change the type definition in next.d.ts:

declare module 'next/app' {
  type AppProps<P = Record<string, unknown>> = {
    Component: NextComponentType<NextPageContext, any, P>;
    router: Router;
    __N_SSG?: boolean;
    __N_SSP?: boolean;
    session?: Session;
    pageProps: P ;
  };
}

so far is handling the typescript setup. the error in your code the way how you destructed the code

const {Component,pageProps}=props

this was wrong. Should be:

 const { Component, session, ...pageProps } = props;

...pageProps means spread the rest of the props. It actually looks like this

 const { Component, session,firstProps,secondProps } = props;

then you need to pass this session to the component too.

   <Component {...pageProps} session={session}/>

CodePudding user response:

The easiest way (and wrong) to fix this error is add any type on line 33:

<SessionProvider session={(pageProps as any).session}>
  • Related