Middleware not redirecting server functions

Lot of resources (even vercel team members have videos on this) recommend middleware for authentication.

But recently I encountered problem when server functions are not properly redirected in middleware.

I describe it here

Can someone have a look/help?

Middleware is ok for authentication (checking who a user is), but not for authorization (checking if a user is allowed to do something) which is what you’re looking at here

You should check this manually in every server function before you perform the action.

Thanks for response. But like I said in that post I do check in server function but problem is that server function is never invoked due to “redirect” in middleware. Instead server function just returns undefined (see this one too).

@jacobparis

You can bypass middleware for your functions based on the next-action header

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    {
      source:
        '/((?!api|_next/static|_next/image|media|fonts|favicon.ico|favicon.png).*)',
      missing: [
        // Exclude Server Actions
        { type: 'header', key: 'next-action' },
      ],
    },
  ],
};

That makes more sense! That solution was from gh issue I linked but initially i thought it was based on checking “api” in routes - and thought it would not work. It seems it checks header.

I will verify if it works tomorrow.

It would be nice to add this info in Nextjs docs don’t you think? Especially like I said lots of guides (even from vercel team) use middleware for authentication/authorization afaik.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.