-
What is the best practice for wrapping my API routes? I mean I can wrap my pages with _app.js/tsx and handle things like authentication at a single point. It feels like there should be a similar solution for api routes but I couldn't find it yet. I'm going to create my wrappers and import them into every api but a generic solution would be definitely cleaner. |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 12 replies
-
@zoozalp I think you are talking about middlewares? If so here's an example of a simple one: // hello.js
import { serialize } from "cookie";
const hello = (handler) => async (req, res) => {
res.setHeader("Set-Cookie", serialize('hello', 'world'));
return handler(req, res);
}
export { hello }; How you use it: // pages/api/hello-cookie.js
import { hello } from './hello';
export default hello((req, res) => {
return res.status(200).json({ message: "A cookie was set in this route by a middleware."})
}); If you are referring to set a middleware that affects all API routes I think that's not possible 🤔. |
Beta Was this translation helpful? Give feedback.
-
Lets try next-connect :) very ok |
Beta Was this translation helpful? Give feedback.
-
I just want to bump this issue. We really need some kind of central route wrapping definition. It gets tricky because NextJS API routes are built to be distributed as standalone serverless functions, which means at build time the routes manifest would need to be read, and code generated to wrap the functions. |
Beta Was this translation helpful? Give feedback.
-
any updates on this? |
Beta Was this translation helpful? Give feedback.
-
Still could use this logic, so we can reduce all the redundant code |
Beta Was this translation helpful? Give feedback.
-
I made middleware to check auth for my api routes. I create functions for each method and then wrap the export in a higher-order function that authenticates the method/route. Here is an example from something I'm working on at moment with Typescript: middleware/withProtect.ts
apis/getAllUsers.ts
pages/api/users/index.ts
|
Beta Was this translation helpful? Give feedback.
-
Hey folks! Here's a real world example of how you can do exactly this with a helper function: https://github.com/steven-tey/dub/blob/main/lib/auth.ts#L33-L118 And here's how you use it in an API route: https://github.com/steven-tey/dub/blob/main/pages/api/projects/%5Bslug%5D/index.ts The cool thing about this approach is you can even pass data from the helper function to your API route (and vice versa) 😃 |
Beta Was this translation helpful? Give feedback.
@zoozalp I think you are talking about middlewares? If so here's an example of a simple one:
How you use it:
If you are referring to set a middleware that affects all API routes I think that's not possible 🤔.