next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

Error: `headers` was called outside a request scope, when using Authjs v5.0.0-beta.19 and next dev --turbo

Open cogb-jclaney opened this issue 1 year ago • 32 comments

Environment

  System:
    OS: Linux 5.15 Ubuntu 22.04.4 LTS 22.04.4 LTS (Jammy Jellyfish)
    CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1265U
    Memory: 5.33 GB / 15.47 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 22.0.0 - ~/.nvm/versions/node/v22.0.0/bin/node
    npm: 10.5.1 - ~/.nvm/versions/node/v22.0.0/bin/npm
  npmPackages:
    @auth/drizzle-adapter: ^1.2.0 => 1.2.0 
    next: ^14.2.3 => 14.2.3 
    next-auth: ^5.0.0-beta.18 => 5.0.0-beta.19 
    react: ^18.3.1 => 18.3.1 

Reproduction URL

https://github.com/cogb-jclaney/authjs-issue

Describe the issue

When running a Next JS site using Authjs v5.0.0-beta.19 and next dev --turbo, I get the following error - "Error: headers was called outside a request scope", running next dev without the --turbo flag works as previous.

Authjs v5.0.0-beta.18 next dev (works) next dev --turbo (works)

Authjs v5.0.0-beta.19 next dev (works) next dev --turbo (causes the error)

image

How to reproduce

Running the command "npm run dev" when "--turbo" is enabled cause the application to error. Running the command without "--turbo" works normally and both with and without work on the previous version (v5.0.0-beta.18).

Credential provider has been configured for the example, no inputs actually needed, user has been hardcoded.

Expected behavior

The session from "await auth()" should be returned.

cogb-jclaney avatar Jun 05 '24 04:06 cogb-jclaney

I am getting this: Error: Invariant: headers() expects to have requestAsyncStorage, none available.

"use client";

import { SessionProvider } from "next-auth/react";
import { getServerSession } from "next-auth";

import React, { ReactNode } from "react";
import { Toaster } from "react-hot-toast";

export default function Providers({ children }: { children: ReactNode }) {
  const session = getServerSession();

  console.log('straight from providers,,', session)

  return (
    <SessionProvider session={session}>
      <Toaster position="top-center" reverseOrder={false} />
      {children}
    </SessionProvider>
  );
}

What am I doing wrong? I need this to access useSession in client components but it does not work.

EDIT: I dont know how to do this in Next14 layouts:

import { SessionProvider } from "next-auth/react"

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}

Qodestackr avatar Jun 05 '24 12:06 Qodestackr

@Qodestackr I would like to point out that wrapping your app directly with sessionprovider doesnot work instead import it in a client component and then wrap that component around your app LIKE THIS:

  return (
    <html lang="en">
      <body className={inter.className}>
        <AuthProvider>
          <Toaster />
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

And for the component

"use client";
import { SessionProvider } from "next-auth/react";

export default function AuthProvider({ children }) {
  return <SessionProvider>{children}</SessionProvider>;
}

Ali-Raza764 avatar Jun 08 '24 05:06 Ali-Raza764

First thing first why did you write "use server" on the server component By default it was server component by marking you have made it a server action that works like a post request

"use server";

import { auth } from "@/lib/auth";

export async function User() {
  const session = await auth();
  return <h1>{session?.user?.name}</h1>;
}```


Ali-Raza764 avatar Jun 08 '24 05:06 Ali-Raza764

const session = getServerSession(); In a client marked component ? @Qodestackr

Ali-Raza764 avatar Jun 08 '24 05:06 Ali-Raza764

import xior from "xior" import { auth } from "@/auth"

const iApi = xior.create({
	baseURL: API_URL,
	headers: {
		"Content-Type": "application/json",
		"Accept": "application/json",
		"Cache-Control": "no-store",
	},
})
iApi.interceptors.request.use(
	async (config) => {
		try {
			const session = await auth()
			console.log("🚀 ~ session:", session)
			config.headers.Authorization = `Bearer ${session?.user.access_token}`
			return config
		} catch (_) {
			toast.error("Erro de Autenticação. Não foi possível obter o token de acesso. Tente novamente mais tarde.")
			return Promise.reject(_)
		}
	}
)

Same error here, in any beta version of next-auth

matbrgz avatar Jun 10 '24 04:06 matbrgz

First thing first why did you write "use server" on the server component By default it was server component by marking you have made it a server action that works like a post request

Thanks, I think I just overlooked that when I was trying different things in hope, I've removed it now and still get the issue.

cogb-jclaney avatar Jun 10 '24 23:06 cogb-jclaney

I just have the same issue

"use client";

const Parent = ({component}: {component: ReactNode}) => {
   // ---- other work
   return (
     <div>
        {component}
    </div>
   )
}
const ServerComponent= ({id}: {id: string})=> {
    const session = await auth();
    return (
        // ----
    )
}

const X = () => {
    const id = "xxxx";
    return (
       <Parent
          component={<ServerComponent id={id}/>}
       />
    )
}

this cause the issue:

Uncaught (in promise) Error: `headers` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context

bilalesi avatar Jun 11 '24 15:06 bilalesi

I create a file get-session.tsx

"use server"
import { auth } from "@/auth"

export async function getCurrentUser() {
	const session = await auth()
	return session
}

and it finally works.

matbrgz avatar Jun 12 '24 00:06 matbrgz

I tried cloning and running the repository but it does not seen to work even after installing all the modules.

$ npm run dev

[email protected] dev next dev 'next' is not recognized as an internal or external command, operable program or batch file.

Ali-Raza764 avatar Jun 12 '24 09:06 Ali-Raza764

I have myself implemented basic authentication using authjs and mongo db along with credentials and oauth providers and also implemented basic stripe payment . Take a look at the repository Here Next-auth-toolkit

Ali-Raza764 avatar Jun 12 '24 10:06 Ali-Raza764

Also the official documentation suggests to create the auth.js file in the root of the directory. Docs

Ali-Raza764 avatar Jun 12 '24 10:06 Ali-Raza764

Hey @Ali-Raza764 thanks, odd it doesn't work for you, works for me doing the below

git clone https://github.com/cogb-jclaney/authjs-issue.git authtest
npm i
npm run dev

My app/auth works when running 'npm run dev' (next dev) The issue is when I try use the --turbo flag 'npm run dev' (next dev --turbo) it crashes with the error above which only happens on beta.19 worked fine on beta.18

cogb-jclaney avatar Jun 14 '24 00:06 cogb-jclaney

Interesting... I'm getting the same error only when I have the --turbo flag

jellohouse avatar Jun 27 '24 22:06 jellohouse

For now yes I removed the turbo flag... but development without it is a lot slower so it's not ideal

jellohouse avatar Jun 28 '24 13:06 jellohouse

Any update here? Local dev sucks without using turbo.

sbassalian avatar Aug 08 '24 14:08 sbassalian

Any update here? Local dev sucks without using turbo.

Spoke too soon lol. Using versions

    "next": "14.2.5",
    "next-auth": "5.0.0-beta.18",

and working

sbassalian avatar Aug 08 '24 14:08 sbassalian

@sbassalian I tried using those versions but the problem remains.

tbouasli avatar Aug 20 '24 14:08 tbouasli

having the same problem with turbo: Error: headers was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context

"next": "14.2.6" "next-auth": "5.0.0-beta.20"

came avatar Aug 27 '24 12:08 came

Any update here? Local dev sucks without using turbo.

Spoke too soon lol. Using versions

    "next": "14.2.5",
    "next-auth": "5.0.0-beta.18",

and working

worke just fine for me 👍

wilfreud avatar Aug 31 '24 21:08 wilfreud

I am getting the same but with "next-auth": "^4.24.7",

tconroy avatar Aug 31 '24 22:08 tconroy

@wilfreud That's odd, if it's working for some people and others not, I don't think it's a version problem.

tbouasli avatar Sep 01 '24 15:09 tbouasli

I got the same issue just random problem

keven-bardales avatar Sep 05 '24 03:09 keven-bardales

Same issue, I found migrating the pages/api routes to be app router api routes solved the problem initially. That is a lot more work, the documentation appears to say I should be able to use auth(req, res)

Tigatok avatar Sep 08 '24 22:09 Tigatok

Same issue

    "next": "14.2.7",
    "next-auth": "5.0.0-beta.20",

I have also tried with [email protected] and [email protected]

Mnigos avatar Sep 09 '24 14:09 Mnigos

@wilfreud I don't think the version is the variable here, you are probably doing something different than us for it to work, could you share a snippet of your code of how you are configuring next-auth and using it? Maybe that will reveal what's actually happening for it to work for you.

tbouasli avatar Sep 09 '24 17:09 tbouasli

@wilfreud I don't think the version is the variable here, you are probably doing something different than us for it to work, could you share a snippet of your code of how you are configuring next-auth and using it? Maybe that will reveal what's actually happening for it to work for you.

I actually found the solution and forgot to share it here.

Hey, I may have found the issue. It appears auth() runs on the server, so I used this trick (found somewhere on stack overflow)

"use server";

import { auth } from "./auth";

export async function getAuth() {
  return await auth();
}
  • Defining getAuth as a server action, auth() is from next-auth

Update (ref): https://stackoverflow.com/a/78501195/19987002

wilfreud avatar Sep 09 '24 17:09 wilfreud

@wilfreud I don't think the version is the variable here, you are probably doing something different than us for it to work, could you share a snippet of your code of how you are configuring next-auth and using it? Maybe that will reveal what's actually happening for it to work for you.

I actually found the solution and forgot to share it here.

Hey, I may have found the issue. It appears auth() runs on the server, so I used this trick (found somewhere on stack overflow)

"use server";

import { auth } from "./auth";

export async function getAuth() {
  return await auth();
}
  • Defining getAuth as a server action, auth() is from next-auth

Update (ref): https://stackoverflow.com/a/78501195/19987002

This does not work for me. I get headers error in "return await auth();"

bonadio avatar Sep 09 '24 17:09 bonadio

@wilfreud this was mentioned before in this issue by @matbrgz, although it might work, I don't see it as an definitive fix, just a workaround, but it's better than nothing. Thanks for sharing.

I create a file get-session.tsx

"use server"
import { auth } from "@/auth"

export async function getCurrentUser() {
	const session = await auth()
	return session
}

and it finally works.

tbouasli avatar Sep 10 '24 15:09 tbouasli

@wilfreud I don't think the version is the variable here, you are probably doing something different than us for it to work, could you share a snippet of your code of how you are configuring next-auth and using it? Maybe that will reveal what's actually happening for it to work for you.

I actually found the solution and forgot to share it here.

Hey, I may have found the issue. It appears auth() runs on the server, so I used this trick (found somewhere on stack overflow)

"use server";

import { auth } from "./auth";

export async function getAuth() {
  return await auth();
}
  • Defining getAuth as a server action, auth() is from next-auth

Update (ref): https://stackoverflow.com/a/78501195/19987002

This solution does not work for me either...

Still getting Uncaught (in promise) Error: `headers` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context

How is there no official fix for this yet... it's been months!

jellohouse avatar Sep 12 '24 20:09 jellohouse

Eu crio um arquivo get-session.tsx

"use server"
import { auth } from "@/auth"

export async function getCurrentUser() {
	const session = await auth()
	return session
}

e finalmente funciona.

This tip worked for me

raffael-sicoob avatar Oct 02 '24 21:10 raffael-sicoob