Skip to content

Should clerkMiddleware be fed async function and use auth.protect() instead of auth().protect()? #6

@vanderlindenma

Description

@vanderlindenma

I am having issues reproducing the route protection step.

With

auth().protect()

I am getting TypeError: auth(...).protect is not a function.

And with auth.protect() instead I get

 ⨯ unhandledRejection: Error: NEXT_REDIRECT
    at nextjsRedirectError (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/nextErrors.js:30:17)
    at redirectToSignInError (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/nextErrors.js:37:3)
    at eval (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/clerkMiddleware.js:144:72)
    at handleUnauthenticated (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/protect.js:24:16)
    at eval (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/protect.js:35:14)
    at Function.eval [as protect] (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/clerkMiddleware.js:153:145)
    at eval (webpack-internal:///(middleware)/./src/middleware.tsx:17:14)
    at eval (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/clerkMiddleware.js:99:50)
    at AsyncLocalStorage.run (node:internal/async_local_storage/async_hooks:91:14)
    at eval (webpack-internal:///(middleware)/./node_modules/@clerk/nextjs/dist/esm/server/clerkMiddleware.js:97:75) {
  digest: 'NEXT_REDIRECT;replace;http://localhost:3000/dashboard;307;',
  clerk_digest: 'CLERK_PROTECT_REDIRECT_TO_SIGN_IN',
  returnBackUrl: 'http://localhost:3000/dashboard'

Looked up the Clerk doc at https://clerk.com/docs/references/nextjs/clerk-middleware and it seems they recommend:

  • auth.protect()
  • AND feed clerkMiddleware an asyn function

From https://clerk.com/docs/references/nextjs/clerk-middleware:

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

const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/forum(.*)'])

export default clerkMiddleware(async (auth, req) => {
  if (isProtectedRoute(req)) await 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)(.*)',
  ],
}

or maybe the current code is fine ifauth is also imported from @clerk/nextjs/server ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions