Next.js Discord

Discord Forum

App Router route with NextResponse called in an imported function

Answered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
Is it possible to have a separate lib, say do-something.js that has a foo() function that returns a NextResponse.json() immediately for a given route.js, one that imports said lib and calls out foo()? I'd like to break out some reusable logic into separate files so I'm not repeating myself in various route.js files.
Answered by riský
Return the function returning nextresponse
View full answer

3 Replies

Return the function returning nextresponse
Answer
@Alligator mississippiensis just checking to see it it worked
Alligator mississippiensisOP
Thanks @riský . yeah, that would work in some use cases, but for me i was trying to figure out a way to not return a response in some condition. i think if/when nextjs ever supports multiple middlewares i could probably explore that. in the mean time, for my use case, i actually wrapped my response in a try/catch block and build a custom error to handle thrown errors (from other libs external to the route.js file), which cleaned up my custom functions a bit.