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

Error: Invariant: headers() expects to have requestAsyncStorage, none available. #9192

Closed
rorn-prometeus opened this issue Nov 20, 2023 · 13 comments
Labels
bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

Comments

@rorn-prometeus
Copy link

Environment

auth-js beta

Reproduction URL

https://github.com/nextauthjs/next-auth-example

Describe the issue

import { signIn, signOut } from "@/auth"

signIn("credentials", {
email,
password,
redirect: false,
})

when i call this in client side component it give me that error at title but if cut that to another file and mark as use server it work
before version it is ok when using in client side now i confuse

How to reproduce

it would be nice if you can give me example and also how to handle custom error messsage

Expected behavior

it should work the way before but dont know maybe i miss doc

@rorn-prometeus rorn-prometeus added bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Nov 20, 2023
@MauricioKruijer
Copy link

I'm experiencing the same error with Auth0 provider, it happens when I click on this button rendered on root page.tsx

'use client'
import { Session } from 'next-auth'
import { signIn, signOut } from '../../auth'

const LoginButton = () => {
  return (
    <button
      style={{ marginRight: 10 }}
      onClick={() => signIn('auth0')}
      className="text-white"
    >
      Log in <span aria-hidden="true">&rarr;</span>
    </button>
  )
}

@rorn-prometeus
Copy link
Author

I'm experiencing the same error with Auth0 provider, it happens when I click on this button rendered on root page.tsx

'use client'
import { Session } from 'next-auth'
import { signIn, signOut } from '../../auth'

const LoginButton = () => {
  return (
    <button
      style={{ marginRight: 10 }}
      onClick={() => signIn('auth0')}
      className="text-white"
    >
      Log in <span aria-hidden="true">&rarr;</span>
    </button>
  )
}

i think they change to server action that why we have this problem. you can use it as server action. but the error message i am not sure

@sadeghbarati
Copy link

Folowed Upgrade Guide (v5) and got the same issue with CredentialsProvider

@balazsorban44
Copy link
Member

The signIn method you are importing is for server components. For client components, you can keep using the one imported from next-auth/react: https://authjs.dev/reference/nextjs/react#signin

@dev-aku-sapiens
Copy link

Create Server action add 'use server' at the top and Call the function.

@mariawarnes
Copy link

I got this error because I was following this tutorial from Vercel on adding authentication with next-auth to Next.js 14 and didn't have 'use server'; at the top of app/lib/actions.ts (which is ommitted in the tutorial but you can find in the repo here)

@DavidForDev
Copy link

DavidForDev commented Dec 23, 2023

hey, I use Apollo-Graphql and next-auth in this code, I try to pass the user token to the server with "setContext", but I got such an error:

before I clicked on the card (I mean the user card), everything worked fine, and the token was passed to the server, that error appeared after a click on the card.

Error fetching access token: Error: Invariant: Method expects to have requestAsyncStorage, none available


const getAccessToken = async () => {
  try {
    const session = await getServerSession(authOptions);
    return session?.accessToken || "";
  } catch (error) {
    console.error("Error fetching access token:", error);
    return "";
  }
};

getAccessToken().then((res) => {
  console.log(res);
});

const wsLink =
  typeof window !== "undefined"
    ? new GraphQLWsLink(
        createClient({
          url: "ws://localhost:5000/subscriptions",
        })
      )
    : null;

const httpLink = createHttpLink({
  uri: "http://localhost:5000/",
  credentials: "same-origin",
});

const link =
  typeof window !== "undefined" && wsLink != null
    ? split(
        ({ query }) => {
          const def = getMainDefinition(query);
          return (
            def.kind === "OperationDefinition" &&
            def.operation === "subscription"
          );
        },
        wsLink,
        httpLink
      )
    : httpLink;

const authLink = setContext(async (_, { headers }) => {
  try {
    const token = await getAccessToken();

    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : "",
      },
    };
  } catch (error) {
    console.error("Error getting access token:", error);
  }
});

const client = new ApolloClient({
  link: authLink.concat(link),
  cache: new InMemoryCache(),
  uri: "http://localhost:5000/",
  credentials: "include",
});

export default client;

@FleetAdmiralJakob
Copy link

Same error with tRPC and server actions

@jonsoku-dev
Copy link

/**
 * https://github.com/nextauthjs/next-auth/issues/9192
 */

import { auth, signIn, signOut } from "~/libs/auth";

export const Form: React.FC = async () => {
  const au = await auth();
  if (au === null) {
    return (
      <div>
        <h1>Not LoggedIn!</h1>
        <div>
          <h2>Admin</h2>
          <form
            action={async () => {
              "use server";
              await signIn("credentials", {
                email: "jonsoku.dev@gmail.com",
                redirect: false,
              });
            }}
          >
            <button type="submit">Admin User</button>
          </form>

          <h2>Common</h2>
          <form
            action={async () => {
              "use server";
              await signIn("credentials", {
                email: "jonsoku.dev2@gmail.com",
                redirect: false,
              });
            }}
          >
            <button type="submit">Common User</button>
          </form>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div>{JSON.stringify(au, null, 2)}</div>
      <div>
        <form
          action={async () => {
            "use server";
            await signOut();
          }}
        >
          <button type="submit">Sign out</button>
        </form>
      </div>
    </div>
  );
};

it is work
next-auth": "5.0.0-beta.4

@dmarcucci
Copy link

I was simply redirecting to /api/auth/signin if the session could not be found, so not the same setup as the examples above.

In my case, however, I had to disable Turbopack (i.e., --turbo flag) when running next dev locally.

Commenting here just in case anybody else ran into a similar issue.

@AndonMitev
Copy link

If i move the code from client to server action:

'use server';

import { StatusAPIResponse } from '@farcaster/auth-kit';
import { signIn } from 'next-auth/react';

export async function signInAction(res: StatusAPIResponse) {
  signIn('credentials', {
    message: res.message,
    signature: res.signature,
    name: res.username,
    pfp: res.pfpUrl,
    redirect: false
  });
}

then i got :
TypeError: (0 , next_auth_react__WEBPACK_IMPORTED_MODULE_2__.signIn) is not a function at signInAction

if i keep it client then i got

Error: Invariant: headers() expects to have requestAsyncStorage, none available.

so no idea what to do using: "next-auth": "^5.0.0-beta.9",

@colorpackdev
Copy link

Create Server action add 'use server' at the top and Call the function.

Loved this, no extra work, I was following the tutorial as well: https://nextjs.org/learn/dashboard-app/adding-authentication

@isoteriksoftware
Copy link

isoteriksoftware commented Apr 27, 2024

This works for me. Update the import for the auth. Also update the code to include all (or only) the providers your app needs.

You can then import and use in any component.

"use server";

import { signIn as authSignIn } from "../../app/auth";

export const signIn = async (provider: "instagram" | "tiktok" | "youtube") => {
  await authSignIn(provider);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.
Projects
None yet
Development

No branches or pull requests