Clerk Middleware experiencing unexpected malfunctions

After installing Next.js 14 for my project, I decided to set up authentication with Clerk before getting started. Despite configuring the middleware.ts and layout.tsx files and running npm run dev, the terminal showed that the /middleware was compiled. However, upon accessing localhost:3000 in my browser, instead of redirecting to the Clerk sign-in page, it opened the Next.js layout page.

Here is the code snippet:

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", 
});

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

I am currently building a project clone where the tutorial used the deprecated authMiddleware to configure Clerk authentication in Next.js. I have followed the migration to clerkMiddleware but still face redirection issues.

Here is 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).*)',
        '/(apis||trpcs)(.*)',
    ],
};

Answer №1

There seems to be a glaring mistake in the layout - you used clerk provider but forgot to include 'children' within the markup. I can guide you on how to rectify this, so please consider marking this as the answer since I am new to stackoverflow. Thank you.

To fix this issue, insert the following code snippet in your layout and make sure to import everything from clerk:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating Tree Structure Object Automatically from Collection using Keys

I am looking to automatically generate a complex Tree structure from a set of objects, with the levels of the tree determined by a list of keys. For example, my collection could consist of items like [{a_id: '1', a_name: '1-name', b_id ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

What is the best way to launch the Playwright browser in Jest using the setupFilesAfterEnv hook, to ensure accessibility within the test file while incorporating TypeScript?

When using Jest and Playwright, I encountered an issue where I wanted to launch the browser from setupFilesAfterEnv in order to avoid repeating the process in every test file. Despite successfully launching the browser and having global variables accessibl ...

We regret to inform you that an application error has occurred: a critical server-side exception has been encountered during the deployment of the next app. For further details, please refer to the

Seeking assistance urgently! I am facing a recurring error when attempting to deploy my latest app on Vercel. Despite a successful build and deployment of the site, an error persists on the page. The environment variables appear to be correct. Interestingl ...

Refresh the ngrx state data whenever the RouteGuard is triggered

When it comes to ensuring the protected view of an entity, I utilize a RouteGuard to pre-load the necessary data for the desired view into the ngrx store. However, as the corresponding data from the backend can be subject to change over time, it is crucial ...

Unable to assign values using Promises in an Angular component

While working on a Component HTML file, I encountered an issue with exposing a variable. The variable was supposed to retrieve a value from the response using cl.getMonitors. Strangely, despite seeing console.dir(res) in the console, the value of the var ...

Implementing a Toggle Feature in React Components for Looping Elements

Hey everyone, I'm encountering a problem on my development site and could use some assistance. The issue I'm facing involves looping through a data file to create project cards with show more/show less functionality for displaying/hiding descript ...

Define security JWT token in the TypeScript REST API using the swagger annotations

Utilizing typescript-rest and incorporating swagger, a package known as typescript-rest-swagger has been integrated. Efforts to include the Bearer token into swagger have proven unsuccessful thus far. Removing the authorization middleware seems to allow ...

Retrieve the API to extract the language icons from Visual Studio Code and integrate them into the Visual Studio extension

For my extension, I want to display specific items on a tree view with icons representing their language. Instead of saving 90 svgs, I'm exploring the possibility of accessing Visual Studio Code icons directly from the IDE through an API call or other ...

Executing an Observable function in Angular Typescript a single time

Within my Angular application, there exists a service responsible for retrieving data from a server. load.service.ts: load = new Observable(observer => { console.log('load function called'); // asynchronous tasks with time delay obser ...

What is the logic behind using interfaces to declare functions in TypeScript and what exactly is the purpose behind it?

interface SearchFunc { (source: string, subString: string): boolean; } It is common for me to define a function in this manner: type Search = (source:string,subString:string)=>void I am curious about why TypeScript allows the use of interfaces to de ...

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

Create an HTML button on the homepage that directs users to the "about" page

I've been struggling to make a button in my Ionic app navigate to a different page upon clicking. Despite being new to Ionic, I've spent hours trying to solve this issue. Below is the HTML code in home.page.html: <ion-header> &l ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Challenges arising from the implementation of dependencies in gateways and other modules

Having been using nestjs for a while, I have found it to be incredibly useful, especially as projects become larger and more complex. However, I am currently facing an issue with dependency injection. I have always used it between modules of the same type ...

Reorganizing Firebase data in Ionic 2

I am currently working on an exciting project to develop an Ionic notes application, where users can easily rearrange items in the list using the reorderArray() function. However, I encountered an issue with Firebase resulting in an error message related t ...

Tips for determining data type in TypeScript without using the 'instanceof' operator

Attempting to upgrade a basic custom Link component in React to TypeScript has been a challenge. Below is the initial code for the simple Link component written in JavaScript: import React from "react"; import { Link as RouterLink } from "r ...

When utilizing the OnPush strategy, the view of the child component does not undergo re-rendering

@Component({ selector: "parent", template: `<child [userId]="(userID$ | async)"></child>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ParentComponent implements OnInit { userID$: BehaviorSubject<string> ...

Passing user inputs from the view to the component in Angular 15

I'm new to Angular and currently developing a project with Angular 15. In my .ts component, I am fetching information from an API: export class CustomPersonalSettingsComponent implements OnInit { constructor( private personalSettingsSe ...

Loopback 4: Transmitting associated information

In my registration form, I have the option to add one or more addresses for a user. In order to streamline this process, I am using loopback: { "id": 0, "name": "User Name", "addresses": [ { "street": "xx", "city": "xx", "count ...