Route Handler Wrapper
Unanswered
Crazy ant posted this in #help-forum
Crazy antOP
Is it possible to create wrapper for Next JS 15 Route Handler ? I want to create wrapper for catching global errors, logging, and authentication middleware
11 Replies
Spectacled bear
I think you can create
500.tsx
or error.tsx
file to do the same.Crazy antOP
i need it for the server api part (route.ts) not the client part
Spectacled bear
Generally, you wrap the api end points with try catch block to take care.
Crazy antOP
Yeah, but i should wrap every api with same code. It can be quite cumbersome and messy. I'm looking for cleaner way like middleware in express
Yes, I believe you should be able to make wrappers, as long as you’re returning the correct function signature (expected by Next.js in order to make routes out of them)
Remember, the names they end up having need to be one of the valid: GET, POST, PUT, etc.
Remember, the names they end up having need to be one of the valid: GET, POST, PUT, etc.
And only these allowed functions are allowed to be exported from
route.ts
filesSomething like this is what
next-auth
does.@Crazy ant Yeah, but i should wrap every api with same code. It can be quite cumbersome and messy. I'm looking for cleaner way like middleware in express
Southern rough shrimp
Next.js has
middleware.ts
which is executed on every request I believe@LuisLl Something like this is what `next-auth` does.
Middleware in Next.js isn’t like the middlewares in Express tho. I think he wants a way to centralize the repeating logic instead of writing the boilerplate in every route, and maybe multiple times per route.ts file.
Idk if a wrapper like this will solve that issue, but you can try
Idk if a wrapper like this will solve that issue, but you can try
just
/api/[[...path]]/route.ts
one single route handler for all your routes