Search code examples
typescriptauthenticationnext.jsclerk

Clerk getAuth() helper inside of api folder returns: { userId: null }


completely stumped here..

Working with clerk, and I want to access current users userId with the getAuth() helper.

Docs here: https://clerk.com/docs/references/nextjs/get-auth

pages/api/example.ts

import { getAuth } from "@clerk/nextjs/server";
import type { NextApiRequest, NextApiResponse } from "next";
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { userId } = getAuth(req);
  // Load any data your application needs for the API route
  return res.status(200).json({ userId: userId });

Now, when I visit this endpoint in my browser at:

http://localhost:3000/api/example

It seems to be working, as I see the userId printed in my browser:

{"userId":"user_2Ze2xqQyKbZbsXaZi7cv1sXLf2S"}

However, when I try calling this API endpoint in a getServerSideProps function, I recieve: { userId: null }

pages/profile.tsx

export async function getServerSideProps() {

    const res = await fetch(`http://localhost:3000/api/example`);
    const data = await res.json()

    console.log(data) // this logs: { userId: null } 

    return {
        props: {
            properties: data,
        },
    };
}

My middleware file:

middleware.ts

import { authMiddleware } from "@clerk/nextjs";
 
export default authMiddleware({
  publicRoutes: ["/api/example", "/profile"],
});
 
export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

Can anyone spot an issue? Been stuck on this all day. Thanks for looking


Solution

  • The problem is that the request made from getServerSideProps() will be missing any identifying headers / cookies / etc.

    Since both the API route handler and getServerSideProps() run in the same server-side context, you should not need to make an extra internal request.

    Simply use getAuth() within getServerSideProps

    export function getServerSideProps({ req }) {
      const { userId } = getAuth(req);
    
      return {
        props: {
          properties: { userId },
        },
      };
    }