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: Clerk: auth() and currentUser() are only supported in App Router (/app directory). #1642

Closed
7 of 21 tasks
VaniaPopovic opened this issue Aug 28, 2023 · 16 comments
Closed
7 of 21 tasks
Labels
needs-reproduction Awaiting a minimal reproduction

Comments

@VaniaPopovic
Copy link

VaniaPopovic commented Aug 28, 2023

  • I have reviewed the documentation
  • I have searched for existing issues
  • I have ensured I am on the most recent version, and checked the changelog for that version
  • I have provided the Frontend API key from my application dashboard:pk_test_bWVycnktc3R1cmdlb24tNTkuY2xlcmsuYWNjb3VudHMuZGV2JA
  • I have provided a minimal reproduction or replay recording below

Brief Summary of the Issue

Clerk is complaining about the usage of currentUser in app router.
I have extracted a common auth function under /lib/auth.

snippet of it can be found here:

import type { User } from "@clerk/nextjs/server";
import { currentUser } from "@clerk/nextjs/server";

type ApiResponse =
  | { status: 200; data: User }
  | { status: 401; message: string };

const userAuth = async (): Promise<ApiResponse> => {
  const user = await currentUser();

  if (!user) {
    return { status: 401, message: "Unauthorized" };
  }
  return { status: 200, data: user };
};

export default userAuth;

When I import it in to a Apps Dir route handler I get the following error:

Error: Clerk: auth() and currentUser() are only supported in App Router (/app directory).
If you're using /pages, try getAuth() instead.
Original error: Error: Invariant: headers() expects to have requestAsyncStorage, none available.

Minimal Reproduction or Replay

A reproduction of the repo can be found at : https://github.com/VaniaPopovic/clerk_repro

Browser/OS

Chrome 116.0.5845.111, Node 19.8.1 ,

Package + Version

  • @clerk/clerk-js
  • @clerk/clerk-react
  • @clerk/nextjs 4.23.3
  • @clerk/remix
  • @clerk/types 3.50.0
  • @clerk/themes
  • @clerk/localizations
  • @clerk/clerk-expo
  • @clerk/backend
  • @clerk/clerk-sdk-node
  • @clerk/shared
  • @clerk/fastify
  • @clerk/chrome-extension
  • gatsby-plugin-clerk
  • build/tooling/chore
  • other:
@jescalan
Copy link
Contributor

jescalan commented Sep 6, 2023

It looks like the error is fairly clear here. Did you try using getAuth() instead to see if it would resolve your issue?

@VaniaPopovic
Copy link
Author

It looks like the error is fairly clear here. Did you try using getAuth() instead to see if it would resolve your issue?

https://clerk.com/docs/quickstarts/nextjs states to use currentUser() or auth() if I'm using the app router which is exactly what I'm doing.

I thought getAuth() is for the pages router? If that's the case I am not using the pages router.

@panteliselef
Copy link
Member

@VaniaPopovic have you tried moving the userAuth file directly below the app directory ?

@royanger
Copy link
Member

I tested your repro @VaniaPopovic (only changed to my dev keys) and I am not getting the error. The api/works route was returning a 500 error until I swapped to NextResponse.json. Anything in particular that needs doing to reproduce the error?

@jescalan jescalan added the needs-reproduction Awaiting a minimal reproduction label Sep 12, 2023
@VaniaPopovic
Copy link
Author

Sorry for the delay in the reply, I was away on holidays. I have debugged this more, as I was developing on my mac machine without any issues. The problem arises only on a windows machine if this helps!

@royanger
Copy link
Member

royanger commented Oct 2, 2023

Hi @VaniaPopovic. Can you let me know which version of Windows, and if you were using Windows directly for WSL and any other info you can provide? Thanks.

@kasperp
Copy link

kasperp commented Nov 1, 2023

Hi, I'm experience the same issue. I'm on Windows 11 and only when running my next application on the development server.

This is my experience:

  • Run npm run dev
  • App works
  • Make a change to a source file
  • App crashes with:
image image

Starting and stopping the dev server and the app works again

@jescalan
Copy link
Contributor

We are still waiting on a reproduction here, just a small update!

@Burshan
Copy link

Burshan commented Dec 12, 2023

@VaniaPopovic @royanger @jescalan I'm facing the same error. I created a file under the /lib directory dedicated to API management. However, when attempting to leverage Clerk.js for user authentication, I'm consistently facing this error message. Also tried moving the file directly under /app directory and haven't been able to resolve the issue.
Not sure that the error's suggestion relevant to me since i am using app router structure and not pages.
Thats the api management snippet:

import { auth } from "@clerk/nextjs";
import prismadb  from "./prismadb";

export const incrementApiLimit = async () => {
  const { userId } = auth();

  if (!userId) {
    return;
  } 

  const userApiLimit = await prismadb.userApiLimit.findUnique({
    where: { userId: userId }
  });

  if (userApiLimit) {
    await prismadb.userApiLimit.update({
      where: { userId: userId },
      data: { count: userApiLimit.count + 1 },
    });
  } else {
    await prismadb.userApiLimit.create({
      data: { userId: userId, count: 1 },
    });
  }
};

@VaniaPopovic
Copy link
Author

VaniaPopovic commented Dec 13, 2023

Hi, the issue is happening on my machine with Windows 11 Version 10.0.22621 Build 22621 , not using WSL.
I have tried setting up Julius' https://github.com/juliusmarminge/acme-corp on my machine aswell, and it's failing with the same issue. When disabling runtime="edge", it runs without problems. I think that can be used as a better repro than mine.

Tested the same repo on my mac, and I get no problems.

@VaniaPopovic
Copy link
Author

You can try out my fork aswell if you like https://github.com/VaniaPopovic/acme-corp

  • I just forked the repository
  • Created a .env local with my clerk repro project credentials
  • Ran pnpm i
  • Ran pnpm dev:web

I get the following output

@acme/nextjs:dev:  ✓ Ready in 2.5s
@acme/nextjs:dev:  ○ Compiling /src/middleware ...
@acme/nextjs:dev:  ✓ Compiled /src/middleware in 542ms (273 modules)
@acme/nextjs:dev:  ○ Compiling /(marketing)/page ...
@acme/nextjs:dev:  ✓ Compiled /(marketing)/page in 2.2s (5240 modules)
@acme/nextjs:dev:  ⨯ Internal error: TypeError: Cannot read properties of undefined (reading '')
@acme/nextjs:dev:     at resolveClientReference (../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.development.js:63:43)
@acme/nextjs:dev:     at resolveModule (../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.development.js:1956:25)
@acme/nextjs:dev:     at processFullRow (../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.development.js:2032:9)
@acme/nextjs:dev:     at processBinaryChunk (../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.development.js:2180:7)
@acme/nextjs:dev:     at progress (../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.development.js:2267:5)
@acme/nextjs:dev: [TypeError: Cannot read properties of undefined (reading '')]
@acme/nextjs:dev:  ⨯ [TypeError: Cannot read properties of undefined (reading '')]
@acme/nextjs:dev:  ⨯ [TypeError: Cannot read properties of null (reading 'default')]

And just a blank Internal server error white page on the desktop
I think in newer versions of clerk ( that repo hasn't been updated in a while ) the error isn't swallowed but instead produces the error I posted initially.

@jescalan
Copy link
Contributor

@VaniaPopovic Are you sure this error is related to auth() and currentUser() support in app directory? If not, but you still would like the error to be looked at, it would be great if you could open it as a different issue 🙏

@jescalan
Copy link
Contributor

Related issue: vercel/next.js#52176

@VaniaPopovic
Copy link
Author

Hi @jescalan , I will close this issue in favour of opening a new one. Thanks

@gilish-tech
Copy link

This Clerk error is very annoying. I should have encountered this error during development, not in production. The problem is with the "src" folder; it makes Clerk think it's a page route

@marvinmarnold
Copy link

The problem in my case was that at the bottom of my ssr client. export const supabaseServerClient = createClerkSupabaseClientSsr() must be removed and instead call createClerkSupabaseClientSsr from with React component.

import { auth } from "@clerk/nextjs/server";
import { createClient } from "@supabase/supabase-js";

import { Database } from "../../utils/supabase/database.types";

export function createClerkSupabaseClientSsr() {
	// The `useAuth()` hook is used to access the `getToken()` method
	const { getToken } = auth();

	return createClient<Database>(
		process.env.NEXT_PUBLIC_SUPABASE_URL!,
		process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
		{
			global: {
				// Get the custom Supabase token from Clerk
				fetch: async (url, options = {}) => {
					const clerkToken = await getToken({
						template: "supabase",
					});

					// Insert the Clerk Supabase token into the headers
					const headers = new Headers(options?.headers);
					headers.set("Authorization", `Bearer ${clerkToken}`);

					// Now call the default fetch
					return fetch(url, {
						...options,
						headers,
					});
				},
			},
		}
	);
}

export const supabaseServerClient = createClerkSupabaseClientSsr();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-reproduction Awaiting a minimal reproduction
Projects
None yet
Development

No branches or pull requests

8 participants