How do I set up a public API with route handlers and server components?
Answered
Rhinelander posted this in #help-forum
RhinelanderOP
I'm currently setting up my nextjs app with the app router and reading the article linked below:
https://vercel.com/blog/common-mistakes-with-the-next-js-app-router-and-how-to-fix-them
The app I'm working on requires data fetching from my database in both client and server components – my understanding here is that the best practice is for me to fetch data in route handlers for client components and directly for server components.
If I wanted to open up a public API for my app in the future, how would I do that with this app setup? With the pages router I assume I would have been able to expose my API routes and avoid code duplication, but I'm unsure what the equivalent is for the app router.
https://vercel.com/blog/common-mistakes-with-the-next-js-app-router-and-how-to-fix-them
The app I'm working on requires data fetching from my database in both client and server components – my understanding here is that the best practice is for me to fetch data in route handlers for client components and directly for server components.
If I wanted to open up a public API for my app in the future, how would I do that with this app setup? With the pages router I assume I would have been able to expose my API routes and avoid code duplication, but I'm unsure what the equivalent is for the app router.
Answered by joulev
Same thing, you expose your route handlers. To avoid code duplication, abstract the logic into functions and then call that function in both routes handlers and server components
2 Replies
@Rhinelander I'm currently setting up my nextjs app with the app router and reading the article linked below:
https://vercel.com/blog/common-mistakes-with-the-next-js-app-router-and-how-to-fix-them
The app I'm working on requires data fetching from my database in both client and server components – my understanding here is that the best practice is for me to fetch data in route handlers for client components and directly for server components.
If I wanted to open up a public API for my app in the future, how would I do that with this app setup? With the pages router I assume I would have been able to expose my API routes and avoid code duplication, but I'm unsure what the equivalent is for the app router.
Same thing, you expose your route handlers. To avoid code duplication, abstract the logic into functions and then call that function in both routes handlers and server components
Answer
RhinelanderOP
Oh perfect that makes sense, thank you!