What are you trying to accomplish
I’m encountering an issue with accessing dynamic routes in my Next.js application that uses Clerk for authentication, and the routes are managed by Builder.io. Specifically, I’m getting a 401 Unauthorized
response when trying to access dynamic routes such as /studio/variis
. I need to ensure that these dynamic routes are correctly recognized as public or private by Clerk middleware and can be accessed without authentication issues.
Code stack you are integrating Builder with
Next.js, Clerk for authentication, Builder.io for content management
Reproducible code example
Here is the code for my current middleware setup, which is intended to manage authentication and handle dynamic routes. Despite the configuration, I’m receiving 401 Unauthorized
errors for certain routes.
import { authMiddleware, redirectToSignIn } from '@clerk/nextjs'
import { NextRequest, NextResponse } from 'next/server'
export default authMiddleware({
publicRoutes: [
'/api(.*)',
'/studio(.*)',
'/v2(.*)',
'/sanity-studio(.*)',
'/(.*)' // General catch-all for dynamic routes
],
afterAuth(auth, req) {
const pathname = req.nextUrl.pathname;
// Debug logging
console.log('Request URL:', req.url);
console.log('Is public route:', auth.isPublicRoute);
console.log('User ID:', auth.userId);
console.log('Authorization header:', req.headers.get('authorization'));
// Handle public routes
if (auth.isPublicRoute || pathname.startsWith('/studio') || pathname.startsWith('/variis')) {
return NextResponse.next();
}
// Redirect to sign-in if not authenticated
if (!auth.userId) {
return redirectToSignIn({ returnBackUrl: req.url });
}
// Handle API authentication
if (pathname.startsWith('/api') && !req.headers.get('authorization')) {
if (req.headers.get('authorization') !== `Bearer ${process.env.API_KEY}`) {
return new NextResponse(
JSON.stringify({ success: false, message: 'Authentication failed' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
);
}
}
// Allow other authenticated requests to proceed
return NextResponse.next();
},
});
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)', '/studio(.*)',],
}
I would appreciate any guidance on ensuring that dynamic routes managed by Builder.io are correctly handled by Clerk authentication. Specifically, I need to understand why these routes are being flagged as unauthorized and how to adjust my configuration to resolve this issue.