Error when using clerk getAuth from UploadThing routes

Dear All, I'm having problem using clerk and uploadthing. NextJs: version 13.4.4 React:18.2.0 Uploadthing:5.2.1 Typescript:5.1.6 And using the pages router of nextjs. I tried to isolate the issue as such: I have the uploadthing endpoint and a dummy enpoint using both clerck getAuth(req). dummy.ts
import { getAuth } from '@clerk/nextjs/server'

export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const { userId } = getAuth(req)
// Load any data your application needs for the API route
return res.status(200).json(userId)
}
import { getAuth } from '@clerk/nextjs/server'

export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const { userId } = getAuth(req)
// Load any data your application needs for the API route
return res.status(200).json(userId)
}
` uploadthing.ts
import { createNextPageApiHandler } from 'uploadthing/next-legacy'
import {uploadRouter} from "../../server/upload-routes";

const handler = createNextPageApiHandler({
router: uploadRouter,
})

export default handler
import { createNextPageApiHandler } from 'uploadthing/next-legacy'
import {uploadRouter} from "../../server/upload-routes";

const handler = createNextPageApiHandler({
router: uploadRouter,
})

export default handler
8 Replies
Alex
AlexOP•17mo ago
upload-routes.ts:
import { getAuth } from '@clerk/nextjs/server'
import { createUploadthing, type FileRouter } from 'uploadthing/next-legacy'
import { prisma } from '@app/db'
import { utapi } from 'uploadthing/server'

const f = createUploadthing()

// FileRouter for your app, can contain multiple FileRoutes
export const uploadRouter = {
// Define as many FileRoutes as you like, each with a unique routeSlug
photos: f({ image: { maxFileSize: '4MB' } })
// Set permissions and file types for this FileRoute
.middleware(async ({ req, res }) => {
//todo:Implement the security check here

// This code runs on your server before upload
const {userId} = getAuth(req)

// If you throw, the user will not be able to upload
if (!userId) throw new Error('Unauthorized')

// Whatever is returned here is accessible in onUploadComplete as `metadata`
return {userId}
})
.onUploadComplete(async ({ metadata, file }) => {
// This code RUNS ON YOUR SERVER after upload
console.log("Upload complete for userId:", metadata.userId);

console.log('file url', file.url)
}),
} satisfies FileRouter

export type UploadRouter = typeof uploadRouter
import { getAuth } from '@clerk/nextjs/server'
import { createUploadthing, type FileRouter } from 'uploadthing/next-legacy'
import { prisma } from '@app/db'
import { utapi } from 'uploadthing/server'

const f = createUploadthing()

// FileRouter for your app, can contain multiple FileRoutes
export const uploadRouter = {
// Define as many FileRoutes as you like, each with a unique routeSlug
photos: f({ image: { maxFileSize: '4MB' } })
// Set permissions and file types for this FileRoute
.middleware(async ({ req, res }) => {
//todo:Implement the security check here

// This code runs on your server before upload
const {userId} = getAuth(req)

// If you throw, the user will not be able to upload
if (!userId) throw new Error('Unauthorized')

// Whatever is returned here is accessible in onUploadComplete as `metadata`
return {userId}
})
.onUploadComplete(async ({ metadata, file }) => {
// This code RUNS ON YOUR SERVER after upload
console.log("Upload complete for userId:", metadata.userId);

console.log('file url', file.url)
}),
} satisfies FileRouter

export type UploadRouter = typeof uploadRouter
When trying to upload a file I'm getting this error:
[UT] middleware failed to run
Error: You need to use "authMiddleware" (or the deprecated "withClerkMiddleware") in your Next.js middleware file. You also need to make sure that your middleware matcher is configured correctly and matches this route or page. See https://clerk.com/docs/quickstarts/get-started-with-nextjs
at /Users/aroba/komonco/saas/node_modules/@clerk/nextjs/dist/cjs/server/getAuth.js:45:13
at /Users/aroba/komonco/saas/node_modules/@clerk/nextjs/dist/cjs/utils/debugLogger.js:55:19
at Object.eval [as middleware] (webpack-internal:///(api)/./src/server/upload-routes.ts:22:90)
at eval (webpack-internal:///(api)/../../node_modules/uploadthing/dist/chunk-UNVWQBTP.mjs:330:46)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(api)/../../node_modules/uploadthing/dist/next-legacy.mjs:33:22)
[UT] middleware failed to run
Error: You need to use "authMiddleware" (or the deprecated "withClerkMiddleware") in your Next.js middleware file. You also need to make sure that your middleware matcher is configured correctly and matches this route or page. See https://clerk.com/docs/quickstarts/get-started-with-nextjs
at /Users/aroba/komonco/saas/node_modules/@clerk/nextjs/dist/cjs/server/getAuth.js:45:13
at /Users/aroba/komonco/saas/node_modules/@clerk/nextjs/dist/cjs/utils/debugLogger.js:55:19
at Object.eval [as middleware] (webpack-internal:///(api)/./src/server/upload-routes.ts:22:90)
at eval (webpack-internal:///(api)/../../node_modules/uploadthing/dist/chunk-UNVWQBTP.mjs:330:46)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(api)/../../node_modules/uploadthing/dist/next-legacy.mjs:33:22)
when calling dummy.ts I'm getting the userid. I'm also using getAuth from several other APIs and from my TRPC endpoints...Everything works as expected. middleware.ts:
import { authMiddleware } from '@clerk/nextjs'

export default authMiddleware({
publicRoutes: ['/(.*)'],
})

export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/(api|trpc)(.*)', '/api(.*)'],
}
import { authMiddleware } from '@clerk/nextjs'

export default authMiddleware({
publicRoutes: ['/(.*)'],
})

export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/(api|trpc)(.*)', '/api(.*)'],
}
Any idea?
Josh
Josh•17mo ago
Is this pages or app dir If pages https://discord.com/channels/966627436387266600/1102510616326967306/1131994817245741107 If app dir, use auth not getAuth
Alex
AlexOP•17mo ago
Hi @Josh Thanks for pointing to the solution. I'm happy to see It is not coming from something I did wrong. I did try to apply the solution but I'm getting another error now client side.
Alex
AlexOP•17mo ago
Alex
AlexOP•17mo ago
Yes pages dir I can see it is related to the same error. I'll follow the topic on the uploadthing channel. Meanwhile I will remove the security for development. Going to production next month. We were planning to use uploadthing but if we do not get a proper solution we will have to drop our subscription and implement something ourselves. I would realy want to avoid to do that 😦
Josh
Josh•17mo ago
What's your front end code look like This looks more like a miss configuration than something wrong with ut
Alex
AlexOP•17mo ago
I'll check tomorrow. But the upload works with the previous routes handler and no getAuth...
ronank_
ronank_•16mo ago
I am getting the same error, is there any fix yet for the required string array
Want results from more Discord servers?
Add your server