I’m building a Next.js application using Clerk for authentication, and I’m encountering the following error in the console:
Uncaught (in promise) Error: ClerkJS: Something went wrong initializing Clerk.
at s (clerk.browser.js:2:41560)
at Ge.<anonymous> (clerk.browser.js:2:206055)
at async Ge.load (clerk.browser.js:2:184013)
at async _IsomorphicClerk.loadClerkJS (index.mjs:1496:9)
This error occurs when the page loads, preventing Clerk from initializing properly.
My middleware.ts
file looks like this:
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
const isPublicRoute = createRouteMatcher(["/", "/login", "/register", "/api/webhook"]);
const isAdminRoute = createRouteMatcher(["/admin(.*)"]);
const isProfessionalRoute = createRouteMatcher(["/professional(.*)"]);
export default clerkMiddleware((auth, req) => {
const { userId, has } = auth();
// Allow public routes
if (isPublicRoute(req)) {
return NextResponse.next();
}
// Redirect to sign in for protected routes if not authenticated
if (!userId) {
return auth().redirectToSignIn({ returnBackUrl: req.url });
}
// Protect admin routes
if (isAdminRoute(req)) {
if (!has({ role: "admin" })) {
return NextResponse.redirect(new URL('/', req.url));
}
}
// Protect professional routes
if (isProfessionalRoute(req)) {
if (!has({ role: "professional" })) {
return NextResponse.redirect(new URL('/', req.url));
}
}
// For all other routes, allow access
return NextResponse.next();
});
export const config = {
matcher: [
'/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
],
};
And my app/layout.tsx
:
import type { Metadata } from "next";
import {
ClerkProvider,
SignInButton,
SignedIn,
SignedOut,
UserButton,
} from "@clerk/nextjs";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<ClerkProvider>
<html lang="en">
<body className={inter.className}>
<header>
<SignedOut>
<SignInButton />
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</header>
{children}
</body>
</html>
</ClerkProvider>
);
}
I’ve checked my environment variables and Clerk dashboard settings, but I’m still unable to resolve this issue. Any help would be greatly appreciated!
Verifying environment variables
- Simplifying the middleware