next-auth v5: Bug when using the auth function inside getServerSideProps with nextjs v14
Environment
System: irrelevant
Binaries:
Node: 21.2.0 -
Yarn: 1.22.22 -
npm: 10.2.3 -
pnpm: 9.12.3 -
Browsers: ittrlrbsnz
npmPackages:
next: 14.2.17 => 14.2.17
next-auth: ^5.0.0-beta.25 => 5.0.0-beta.25
react: ^18 => 18.3.1
Reproduction URL
https://github.com/trm217/next-auth-v5beta--nextjs-ssr-bug
Describe the issue
I found that next-auth can't be used inside getServerSideProps functions, when using next-auth v5 beta with Nextjs v14.
Using auth(ctx) inside getServerSideProps yields the following error:
Code that causes this error:
export async function getServerSideProps(
ctx: GetServerSidePropsContext
): Promise<GetServerSidePropsResult<Props>> {
const session = auth(ctx);
return {
props: {
message: !!session ? "Hi! :)" : "You're not logged in.",
},
};
}
How to reproduce
- Clone the reproduction & cd into the folder
- Install dependencies
- Create the env with
npx auth secret - Run the app in dev-mode using
npm run dev - Visit
https://localhost:3000 - Login with the credentials username admin, password admin
- After successful authentication, you'll be redirected to
http://localhost3000where we attempt to load the session inside a getServerSideProps function. You'll see the error being thrown.
Expected behavior
We'd expect the auth function created through the NextAuth function to work as defined in the docs on how to use next-auth v5, where inside SSR within Next.js one should be able to call await auth(getServerSidePropsContext) to retrieve the session.
https://authjs.dev/getting-started/migrating-to-v5 under authentication methods
Hey @trm217, were you able to somehow fix this?
My only option for now is either getting the session clientSide or migrate the to app router (not an option now).
@pedroleung No, I couldn‘t find a sensible way to workaround this issue.
To workaround the issue you could add
transpilePackages: ["next-auth"]
in your next.config.js
@oceandrama can you elaborate on why this (seemingly?) works? Unreal how many people are having this issue without a definitive solution. I'm using v15 but cannot use AuthJS on a legacy pages router getServerSideProps without this flag.