skip to Main Content

I’m Working in a project, while integration clerk with Next.JS. I found the middleware.ts and .env.local for secret keys are not working.

Click this to see directoryenter image description here

Middleware.ts Code:

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

const isPublicRoute = createRouteMatcher(["/sign-in(.*)", "/sign-up(.*)"]);

export default clerkMiddleware((auth, request) => {
  console.log("skhjcbdhjcbhjdcbhjcdbhjdcbhjdcbhjdbhjdbhjdcbghjdcvbw");
  if (!isPublicRoute(request)) {
    auth().protect();
  }
});

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

Root Layout File :

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

const inter = Inter({ subsets: ["latin"] });

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

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

I tried putting my .env.local file and middleware.ts file to /public folder but it didn’t help.

I tried to check whether middleware.ts is working or not by adding a console.log() command but its not getting invoked when a request comes actually.

And I tried using publishableKey="mykey" in ClerkProvided Initialization and its working. So I’m concluding the .env.local file and middleware.ts file is not accessible by Next.js.

How to rectify this issue? Please help me. Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    After Day of Analyzing, I found the reason why .env.local and middleware.ts file did not got involked. Its because i declared this both file inside my app folder. It should be outside the app folder. It should be in the same level of next.config.mjs file. This Dir is the root directory. I changed those files to root directory, and it worked. Refer my director above to understand clearly.

    Thanks


  2. Have you try adding the env in next.config.mjs like below

    .env.local
     
    BACKEND_URL=http://localhost:5005
    
    next.config.mjs
     
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      env: {
        BACKEND_URL: process.env.BACKEND_URL, //add like this
      },
      optimizeFonts: true,
      reactStrictMode: true,
    };
    
    export default nextConfig;
    
    

    for me it works sometimes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search