typescriptnext.jsmiddlewaretsxclerk

Clerk Middleware not functioning as intended


I just installed Next.js 14 for my project and wanted to setup the authentication with clerk before i start the project after setting up the middleware.ts and my layout.tsx file and running npm run dev its showing that the /middleware was compiled in my terminal after accessing localhost:3000 in my browser but its not redirecting to clerk signin page but its opening the Next.js layout page.

Here is my code:

layout.tsx:

import type { Metadata } from "next"; 
import { Inter } from "next/font/google"; 
import "./globals.css"; 
import { ClerkProvider } from "@clerk/nextjs";

const inter = Inter({ 
    subsets: ["latin"], 
    display: "swap", 
// This helps avoid flash of unstyled text (FOUT) 
});

export const metadata: Metadata = { 
    title: "Create Next App", 
    description: "Generated by create next app", 
};

export default function RootLayout({ 
    children, 
}: Readonly<{ 
    children: React.ReactNode; 
}>) { 
    return ( 
        <ClerkProvider> 
            <html lang="en"> 
                <body className={inter.className}>{children}</body> 
             </html> 
        </ClerkProvider> 
     ); 
}

middleware.ts:

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

const isDashboardRoute = createRouteMatcher(["/dashboard(.)"]); 
const isAdminRoute = createRouteMatcher(["/admin(.)"]);

export default clerkMiddleware((auth, req) => { 
    try { 
        // Restrict admin route to users with a specific role 
        if (isAdminRoute(req)) {
             auth().protect({role: "org:admin"}); 
        } else if (isDashboardRoute(req)) { 
            // Restrict dashboard routes to signed-in users 
            auth().protect(); 
        } else { 
            // For all other routes, ensure the user is signed in 
            auth().protect(); 
        } 
     } catch (e) { 
        auth().redirectToSignIn(); 
       } 
});

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)(.*)", 
        ], 
};

Actually I am trying to build a project clone and in the video, the tutor used the depreciated middleware(authMiddleware) to setup the clerk auth in Next.js, so i have read the migration from authMiddleware to clerkMiddleware but still got redirect issues.

My old middleware code:

import { authMiddleware, redirectToSignIn } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";

export default authMiddleware({


    async afterAuth(auth, request) {
        if(!auth.userId && !auth.isPublicRoute){
            return redirectToSignIn({ returnBackUrl: request.url });
        };

        return NextResponse.next();
    },
});

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

Solution

  • it's very obvious mistake in layout you used clerk provider but forgot to use and ill tell you what to modify but pls mark this as answer cus im new on stackoverflow. Thanks

    this is how to do it put this code in layout and import everthing from clerk:

    <clerkProvider/>
       <signedOut>
          <RedirectToSignUp />
       </signedOut/>
       <signedIn>
        <div>
         {children}
        </div>
       </signedIn>