ramon zubiag
ramon zubiag

Reputation: 1

Issues with API Request Authentication using Clerk Authentication in Nexjts app + Chrome extension

I'm encountering issues with API request authentication using Clerk in my Next.js application. Despite following the documentation, my authentication checks are failing, and I'm receiving 401 Unauthorized errors for certain routes.

Here's a brief overview of the critical parts of my setup:

// pages/api/openai/generate.ts
import { NextRequest, NextResponse } from 'next/server';
import OpenAI from 'openai';
import checkLimits from '@/utils/limits';
import { getAuth } from '@clerk/nextjs/server';
import { authenticate } from '@/utils/authenticate';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export async function POST(req: NextRequest) {
  const { userId } = getAuth(req);
  if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const authResult = await authenticate(req);
  if (!authResult.isAuthenticated) return NextResponse.json(authResult, { status: 401 });

  // Additional logic...
}

// middleware.ts
import { authMiddleware } from '@clerk/nextjs/server';

const middleware = authMiddleware({
  publicRoutes: [
    '/api/auth/new-users',
    '/',
    '/api/stripe/webhook',
    '/api/auth/renew-token',
    '/api/openai/generate',
    '/contact',
    '/api/contact',
    '/api/newsletter',
    '/privacy'
  ],
  publishableKey: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
});

export default middleware;

export const config = {
  matcher: [
    '/((?!.+\\.[\\w]+$|_next).*)',
    '/dashboard',
    '/api/((?!.+\\.[\\w]+$|_next).*)',
  ],
};

Despite these configurations, users are authenticated correctly on the frontend, but API requests are failing with authentication errors. Any guidance on what might be causing this issue or how to debug it would be greatly appreciated.

Thank you!

Upvotes: 0

Views: 327

Answers (1)

Andre wijaya
Andre wijaya

Reputation: 29

you need to use createRouteMatcher in your middleware

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

after that you can put your public routes

const isPublicRoute = createRouteMatcher(["/","/api(.*)"])

Upvotes: 0

Related Questions