Next.js Discord

Discord Forum

Clerk Middleware Causing Issues in Production, Works Fine Locally

Unanswered
Himalayan posted this in #help-forum
Open in Discord
Avatar
HimalayanOP
Clerk middleware is causing issues on the production website, but works correctly in my local development build.
I need the middleware to lock the user on either the authentication page or the form page. It is supposed to allow access to the routes once the form is approved.

I also added Content-Security-Policy as shown in https://clerk.com/docs/security/clerk-csp, but it didn't help

Also, let me know if there is a better way of doing this please

# This is my middleware:


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

export default authMiddleware({
  publicRoutes: ["/"],
  async afterAuth(auth, req) {
    try {
      // allow public routes
      if (auth.isPublicRoute) {
        return NextResponse.next();
      }

      // If user tries to access a private route without being authenticated
      if (!auth.userId) {
        return NextResponse.redirect(new URL('/', req.url));
      }

      // continue if the user is signed in and already on the form page
      if (req.nextUrl.pathname === "/form") {
        return NextResponse.next();
      }

      // get formData from firebase database
      const formData = await getOnboardingFormMiddleware(auth.userId)

      // On successful form data fetch
      if (formData?.accountStatus === CoachAccountStatus.APPROVED) {
        return NextResponse.next();
      }

      // Not approved or no form data
      return NextResponse.redirect(new URL('/form', req.url));
    } catch (error) {
      console.error('Middleware error:', error);
      // Fallback to form page on error
      return NextResponse.redirect(new URL('/', req.url));
    }
  },
});

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

0 Replies