WebDevSimplified / parity-deals-clone

MIT License
244 stars 75 forks source link

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

Open vanderlindenma opened 3 days ago

vanderlindenma commented 3 days ago

I am having issues reproducing the route protection step.

With https://github.com/WebDevSimplified/parity-deals-clone/blob/3661f28d75205d3db84d4b86c82ae535acd11272/src/middleware.ts#L12

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:

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 ?

SUGATACHANDA commented 17 hours ago

Async function needs to fed and auth.protect() should be used in place of auth().protect()