2

I'm encountering an issue where userId returned by Clerk's auth() helper is null, even though I'm wrapping my application with the ClerkProvider. Below are the details of my setup and code:

Docs: https://clerk.com/docs/references/nextjs/auth#use-auth-to-retrieve-user-id

export async function CreateProduct(unsafeData: z.infer<typeof productDetailsSchema>) {
    //this returns null
    const { userId }: { userId: string | null } = await auth()
    const { success, data } =  productDetailsSchema.safeParse(unsafeData)

    if (userId === null) {
        return { 
            error: true, 
            message: 'There was an error creating your product. userId is null' 
        }
    } else if (!success) {
        return { 
            error: true, 
            message: 'There was an error creating your product. Request was unsuccesful' 
        }
    }

    const { id } = await createProductDb({ ...data, clerkUserId: userId })

    redirect(`/dashboard/products/${id}/edit?tab=countries`)
}

This is my middleware setup:

import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";

const isPublicRoute = createRouteMatcher([
  '/', 
  '/sign-in(.*)',
  '/sign-up(.*)',
  '/api(.*)'
]) 

export default clerkMiddleware((auth, req) => {
  if (!isPublicRoute(req)) {
    auth.protect();
  }
})

export const config = {
  matcher: [
    // Skip Next.js internals and all static files, unless found in search params
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run for API routes
    '/(api|trpc)(.*)',
  ],
};

Any help would be greatly appreciated!

Expected Behavior: The auth() helper should return the authenticated user's userId.

Actual Behavior: userId is always null.

Clerk and Next Versions: @clerk/[email protected] @clerk/[email protected] [email protected]

1 Answer 1

-1

You can use <ClerkLoaded /> and <ClerkLoading /> components in your dashboard's layout to ensure that clerk's resources are fully loaded before your component renders.

Link to resource: https://clerk.com/docs/components/control/clerk-loaded

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.