I'm trying to create APIs using route handlers in a Next.js 13 app.
Some of these APIs need to read cookies and handle logic to respond with errors if the user is not logged in or if the login has expired. This logic is common to many APIs, and I'd like to handle it in one central place, similar to how layout.js or layout.tsx can be shared across multiple pages.
Is there a feature in route handlers that can perform a role similar to layouts?
This doesn't seem to be covered in the official documentation. Is there another clean way to address the problem I'm facing?
Using middleware seems like a possible solution. However, checking all URLs for all APIs in 'single' middleware file and performing specific logic for certain APIs doesn't seem like a clean approach for maintenance.
I wrapped my route handler as nyarthan commented.
src/app/api/~~~/route.ts
src/libs/server/withAuth.ts