next.js backend, clerk middleware not detecting in backend
Unanswered
Wood Stork posted this in #help-forum
Wood StorkOP
.
62 Replies
Wood StorkOP
@Anay-208 | Ping in replies
@Wood Stork .
Can you share error and the code of middleware here?
Wood StorkOP
so i'm trying to port the server and etc. from express.js, i made login using clerk etc. but on backend it's not working
Make sure middleware file is in src/middleware.ts or if you are not using src dir then (root)/middleware.ts
Wood StorkOP
Context creation failed: Clerk: getAuth() was called but Clerk can't detect usage of clerkMiddleware(). Please ensure the following: - clerkMiddleware() is used in your Next.js Middleware. - Your Middleware matcher is configured to match this route or page. - If you are using the src directory, make sure the Middleware file is inside of it. For more details, see https://clerk.com/docs/quickstarts/nextjs
import { clerkMiddleware } from '@clerk/nextjs/server'
export default clerkMiddleware()
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)(.*)',
],
}
console.log("middleware is running on middleware")
// app/ClientProviders.tsx
"use client";
import { ApolloProvider } from "@apollo/client";
import { ClerkProvider } from "@clerk/nextjs";
import client from "@/lib/apolloClient";
import ThemeProvider from "@/components/Utils/ThemeProvider";
export default function ClientProviders({ children }: { children: React.ReactNode }) {
return (
<>
<ClerkProvider>
<ApolloProvider client={client}>
<ThemeProvider />
{children}
</ApolloProvider>
</ClerkProvider>
</>
);
}
// app/layout.tsx
import type { Metadata } from "next";
import "./globals.css";
import Navbar from "@/components/Layout/Navbar";
import Footer from "@/components/Layout/Footer";
import ClientProviders from "@/app/Providers";
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
title: "Radiowezel",
description: "School radio app powered by Next.js",
icons: {
icon: "/logo.png",
},
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<ClientProviders>
<html lang="pl">
<body className="flex flex-col min-h-screen">
<Navbar />
<main
id="page-content"
className="flex flex-col items-center justify-center flex-grow p-6 bg-bg text-textprimary border-border"
>
{children}
</main>
<Footer />
</body>
</html>
</ClientProviders>
);
}
import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { NextRequest } from 'next/server';
import { readFileSync } from 'fs';
import { join } from 'path';
import resolvers from './resolvers';
import { getAuth } from '@clerk/nextjs/server';
// Load your GraphQL schema from file
const typeDefs = readFileSync(join(process.cwd(), 'graphql', 'schema.graphql'), 'utf8');
// Create your Apollo Server instance
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: process.env.NODE_ENV !== 'production',
});
// Build a cookie header string using req.cookies.getAll()
const context = async (req: NextRequest) => {
const cookieHeader = req.cookies
.getAll()
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join('; ');
console.log("Cookie header:", cookieHeader);
// Use type assertion so getAuth accepts our object
const { userId } = getAuth({ headers: { cookie: cookieHeader } } as any);
console.log("Authenticated userId:", userId);
return { user: userId ? { id: userId } : null, req };
};
// Create the handler using Apollo’s integration
const handler = startServerAndCreateNextHandler(server, { context });
// Export HTTP methods as required by the App Router
export async function GET(request: NextRequest) {
return handler(request);
}
export async function POST(request: NextRequest) {
return handler(request);
}
@Anay-208 | Ping in replies Make sure middleware file is in src/middleware.ts or if you are not using src dir then (root)/middleware.ts
Wood StorkOP
yeah i was trying src/middleware and root/middleware
Wood StorkOP
and with this code, it's my old code i always getting, not authenticated or user is null
// src/app/api/graphql/route.ts
import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { NextRequest } from 'next/server';
import { readFileSync } from 'fs';
import { join } from 'path';
import resolvers from './resolvers'; // adjust the path if necessary
import { getAuth } from '@clerk/nextjs/server';
// Load your GraphQL schema from file
const typeDefs = readFileSync(join(process.cwd(), 'graphql', 'schema.graphql'), 'utf8');
// Create your Apollo Server instance
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: process.env.NODE_ENV !== 'production',
});
// Define the context function accepting NextRequest directly
const context = async (req: NextRequest) => {
const { userId } = getAuth(req);
return { user: userId ? { id: userId } : null, req };
};
// Create the handler using Apollo’s integration
const handler = startServerAndCreateNextHandler(server, { context });
// Export named HTTP methods as required by the App Router
export async function GET(request: NextRequest) {
return handler(request);
}
export async function POST(request: NextRequest) {
return handler(request);
}
but here atleast middleware is working
Wood StorkOP
@Anay-208 | Ping in replies
Show your file structure
Wait you’re using appolo server, why in next tho?
I’ll check it when I’m free in few hours
Wood StorkOP
cuz of graphql
isnt graphql way better than rest api?
graphql/:
schema.graphql
prisma/:
schema.prisma
public/:
changelog.txt logo.png rules.txt songs todo.txt
src/:
app components lib middleware.ts
schema.graphql
prisma/:
schema.prisma
public/:
changelog.txt logo.png rules.txt songs todo.txt
src/:
app components lib middleware.ts
`
but i think i found my issue tho
i didnt created roles in clerk
and now im going to try use clerk roles
Wood StorkOP
also i get
JWT issued at date claim (iat) is in the future. Issued at date: Sun, 02 Mar 2025 12:01:51 GMT; Current date: Sun, 02 Mar 2025 12:01:38 GMT; (reason=token-iat-in-the-future, token-carrier=cookie)
Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.
Schema Introspection Failure
Introspection is disabled on this endpoint. Enable introspection to populate your schema.
Unable to reach server
We were unable to introspect your endpoint. Please enable introspection on your server. (You might still be able to submit operations!)
and that in apollo
@Wood Stork
JWT issued at date claim (iat) is in the future. Issued at date: Sun, 02 Mar 2025 12:01:51 GMT; Current date: Sun, 02 Mar 2025 12:01:38 GMT; (reason=token-iat-in-the-future, token-carrier=cookie)
Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.
That clearly shows the error.
It’s likely that you are building locally with test keys and using the local build in production with production build
It’s likely that you are building locally with test keys and using the local build in production with production build
Wood StorkOP
No i use test productions everywhere
In my .env I use only development version api
@Wood Stork I don't understand
Are you running npm build locally and uploading that build to your server?
Wood StorkOP
Locally
Wood StorkOP
Only
@Anay-208 | Ping in replies Are you running npm build locally and uploading that build to your server?
Wood StorkOP
I run
npm run dev
@Wood Stork
JWT issued at date claim (iat) is in the future. Issued at date: Sun, 02 Mar 2025 12:01:51 GMT; Current date: Sun, 02 Mar 2025 12:01:38 GMT; (reason=token-iat-in-the-future, token-carrier=cookie)
Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.
If you are facing this in dev, You're using a different key for publishable and secret. Confirm your .env file
If not, can you provide a min repro repo?
Wood StorkOP
I use these
Are you sure the correct keys are in .env file?
If you are, you'll have to provide a [min repro repo](https://nextjs-faq.com/minimal-reproduction-repository)
Wood StorkOP
There's a chance I have them in .env instead of .env.local
Wood StorkOP
i don't know whats going on
when i login and refresh then i get the issue
@Anay-208 | Ping in replies If you are, you'll have to provide a [min repro repo](<https://nextjs-faq.com/minimal-reproduction-repository>)
Wood StorkOP
so its minimal code where the issue exists?
i'll try to make it
Wood StorkOP
i cant find whats making this issue
like ive made separate repo with only navbar and login page
and theres no issue of this appears
its soo weird
i also get this
JWT issued at date claim (iat) is in the future. Issued at date: Sun, 02 Mar 2025 17:56:35 GMT; Current date: Sun, 02 Mar 2025 17:56:23 GMT; (reason=token-iat-in-the-future, token-carrier=cookie)
Wood StorkOP
ohh gosh
i fixed it synchronizing my clock
with ntpd
uhh
Context creation failed: Clerk: getAuth() was called but Clerk can't detect usage of clerkMiddleware(). Please ensure the following: - clerkMiddleware() is used in your Next.js Middleware. - Your Middleware matcher is configured to match this route or page. - If you are using the src directory, make sure the Middleware file is inside of it. For more details, see https://clerk.com/docs/quickstarts/nextjs
still get the clerk middleware error tho
Authenticated userId: undefined
now i have this issue
oh gosh
i fixed it all!!
i used auth instead of old getauth