Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Cannot read properties of undefined (reading 'session') #4845

Closed
tszhong0411 opened this issue Jul 5, 2022 · 6 comments
Closed
Labels
triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

Comments

@tszhong0411
Copy link

tszhong0411 commented Jul 5, 2022

Environment

 System:
    OS: Windows 10 10.0.22000
    CPU: (12) x64 Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz
    Memory: 2.66 GB / 15.93 GB
  Binaries:
    Node: 16.15.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 8.11.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22000.120.0), Chromium (100.0.1185.39)
    Internet Explorer: 11.0.22000.120
  npmPackages:
    next: 12.1.7-canary.51 => 12.1.7-canary.51
    next-auth: latest => 4.8.0
    react: ^18 => 18.2.0

Reproduction URL

https://stackblitz.com/edit/nextjs-wqk2hd

Describe the issue

When add the below to get the cookie for the dark mode function. The session is not defined in the pageProps. I think I overrode something so makes this error.

MyApp.getInitialProps = async ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  test: getCookie('test'),
});

I also tried adding the below code, but it happens with another error.

MyApp.getInitialProps = async ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  test: getCookie('test'),
  session: await unstable_getServerSession(ctx.req, ctx.res, authOptions),
});

Error:

./node_modules/openid-client/lib/helpers/deep_clone.js:1:33
Module not found: Can't resolve 'v8'

Import trace for requested module:
./node_modules/openid-client/lib/issuer.js
./node_modules/openid-client/lib/index.js
./node_modules/next-auth/core/lib/oauth/callback.js
./node_modules/next-auth/core/routes/callback.js
./node_modules/next-auth/core/routes/index.js
./node_modules/next-auth/core/index.js
./node_modules/next-auth/next/index.js
./node_modules/next-auth/index.js
./src/pages/_app.tsx

https://nextjs.org/docs/messages/module-not-found

How to reproduce

  1. Clone the next-auth-example repository.
  2. Add the below code in pages/_app.tsx
App.getInitialProps = async ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  test: "test",
})
  1. Run yarn dev to start the server.

Expected behavior

It should be no error.

@tszhong0411 tszhong0411 added the triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. label Jul 5, 2022
@jonrrivera
Copy link

I'm getting the same error on when integrating unstable_getserversession() on my next.js project

Screen Shot 2022-07-05 at 11 14 57 AM

Screen Shot 2022-07-05 at 10 43 59 AM

also, note how on the docs say to add types import type { NextAuthOptions } from 'next-auth' to a [...nextauth].js file ?

Screen Shot 2022-07-05 at 11 18 36 AM

@tszhong0411
Copy link
Author

I don't know what happened. 😢

Snipaste_2022-07-06_15-24-59

@jonathanfrosty
Copy link

jonathanfrosty commented Jul 7, 2022

image

I encountered the same error you are experiencing (shown above) when attempting to retrieve a color scheme cookie with the library Mantine.

I was able to resolve this by first retrieving the initial props and then returning an object that combined them with my custom properties.

import App from 'next/app'
import type { AppContext, AppProps } from 'next/app'
import { getSession } from 'next-auth/react'

// ...

export default function MyApp(props: AppProps) {
  const {
    Component,
    pageProps: { session, ...pageProps },
  } = props

  // ...
}

MyApp.getInitialProps = async (context: AppContext) => {
  const appProps = await App.getInitialProps(context)
  const session = await getSession(context.ctx)

  return {
    ...appProps,
    session,
    colorScheme: getCookie('mantine-color-scheme', context.ctx) || 'light',
  }
}

I'm not sure if it's intended that you should use unstable_getServerSession instead of getSession here, but if I do that then I get the Module not found: Can't resolve 'v8' error.

@tszhong0411
Copy link
Author

tszhong0411 commented Jul 7, 2022

 

@balazsorban44
Copy link
Member

This is expected. unstable_getServerSession is meant for the server-side, as the name suggests. getInitialProps is invoked both server and client-side, so you would need to branch based on eg. typeof window.

@gfazioli
Copy link

Hi there,
I tried to branch in according with typeof window bit it doesn't work

In my current implementation, I'm using the latest version of NextJS and NextAuth

  "dependencies": {
    "@emotion/react": "^11.10.4",
    "@emotion/server": "^11.10.0",
    "@mantine/core": "^5.3.1",
    "@mantine/hooks": "^5.3.1",
    "@mantine/next": "^5.3.1",
    "axios": "^0.27.2",
    "cookies-next": "^2.1.1",
    "next": "12.3.0",
    "next-auth": "^4.10.3",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@types/node": "18.7.16",
    "@types/react": "18.0.18",
    "@types/react-dom": "18.0.6",
    "eslint": "8.23.0",
    "eslint-config-next": "12.3.0",
    "typescript": "4.8.3"
  }

So, I tried to add the NextAuth session in the getInitialProps() and I changed a bit my _app.tsx

import type { NextPage } from "next";
import type { AppProps } from "next/app";
import { ReactElement, ReactNode, useState } from "react";

import {
	ColorScheme,
	ColorSchemeProvider,
	MantineProvider,
} from "@mantine/core";
import { SessionProvider } from "next-auth/react";

// install cookies-next package to manage cookies
import { getCookie, setCookie } from "cookies-next";

import { useColorScheme } from "@mantine/hooks";

// we're going to redefined
export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
	getLayout?: (page: ReactElement) => ReactNode | null;
};

import { unstable_getServerSession } from "next-auth/next";
import { getSession } from "next-auth/react";
import { authOptions } from "pages/api/auth/[...nextauth]";

import App from "next/app";

type AppPropsWithLayout = AppProps<any> & {
	Component: NextPageWithLayout;
};

/**
 * Hello World!! This is the main app component.
 *
 * @param param0
 * @returns
 */
export default function MyApp({
	Component,
	pageProps,
}: AppPropsWithLayout) {
	// Use the layout defined at the page level, if available
	const getLayout = Component.getLayout ?? ((page) => page);

	// hook will return either 'dark' or 'light' on client
	// and always 'light' during ssr as window.matchMedia is not available
	const preferredColorScheme = useColorScheme();

	const [colorScheme, setColorScheme] =
		useState<ColorScheme>(preferredColorScheme);

	console.log("!!!!", { colorScheme, setColorScheme, preferredColorScheme });

	const toggleColorScheme = (value?: ColorScheme) => {
		const nextColorScheme =
			value || (colorScheme === "dark" ? "light" : "dark");
		setColorScheme(nextColorScheme);
		// when color scheme is updated save it to cookie
		setCookie("mantine-color-scheme", nextColorScheme, {
			maxAge: 60 * 60 * 24 * 30,
		});
	};

	return (
		<ColorSchemeProvider
			colorScheme={colorScheme}
			toggleColorScheme={toggleColorScheme}
		>
			<MantineProvider
				withGlobalStyles
				withNormalizeCSS
				theme={{ colorScheme }}
			>
				<SessionProvider session={pageProps.session} refetchInterval={0}>
					{getLayout(<Component {...pageProps} />)}
				</SessionProvider>
			</MantineProvider>
		</ColorSchemeProvider>
	);
}

MyApp.getInitialProps = async (appContext: any) => {
	// calls page's `getInitialProps` and fills `appProps.pageProps`
	const appProps: any = await App.getInitialProps(appContext);

	const colorScheme = getCookie("mantine-color-scheme", appContext) || "dark";

	// check if we're in server side
	if (typeof window === "undefined") {
		// get session from server
		const session = await unstable_getServerSession(
			appContext.req,
			appContext.res,
			authOptions
		);
		return { ...appProps, pageProps: { session, colorScheme } };
	}
	// get session from client
	const session = await getSession();
	return { ...appProps, pageProps: { session, colorScheme } };
};

running pnpm dev I got

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from /Users/giovambattistafazioli/Lavori/InvoiceJet/invoicejet-frontend/.env
error - ./node_modules/.pnpm/openid-client@5.1.9/node_modules/openid-client/lib/helpers/deep_clone.js:1:33
Module not found: Can't resolve 'v8'

Import trace for requested module:
./node_modules/.pnpm/openid-client@5.1.9/node_modules/openid-client/lib/issuer.js
./node_modules/.pnpm/openid-client@5.1.9/node_modules/openid-client/lib/index.js
./node_modules/.pnpm/next-auth@4.10.3_biqbaboplfbrettd7655fr4n2y/node_modules/next-auth/core/lib/oauth/callback.js
./node_modules/.pnpm/next-auth@4.10.3_biqbaboplfbrettd7655fr4n2y/node_modules/next-auth/core/routes/callback.js
./node_modules/.pnpm/next-auth@4.10.3_biqbaboplfbrettd7655fr4n2y/node_modules/next-auth/core/routes/index.js
./node_modules/.pnpm/next-auth@4.10.3_biqbaboplfbrettd7655fr4n2y/node_modules/next-auth/core/index.js
./node_modules/.pnpm/next-auth@4.10.3_biqbaboplfbrettd7655fr4n2y/node_modules/next-auth/next/index.js
./pages/_app.tsx

https://nextjs.org/docs/messages/module-not-found

Do you have any clue?

AbdBarho pushed a commit to LAION-AI/Open-Assistant that referenced this issue Apr 28, 2023
#2946)

see nextauthjs/next-auth#4845
Not sure it fixed or not, since I'm not able to reproduce the issue
locally. Also this might effect the performance, just a bit I think
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.
Projects
None yet
Development

No branches or pull requests

5 participants