Hi all,
Next.js 14 looks amazing to me for a standalone web app, but I'm a bit confused how it fits with products that have multiple interfaces besides just web (e.g. mobile app). All of the examples I see focus on calling the database directly in your server component / server actions, but -- if we have other platforms -- we need a central API to keep everything consistent.
Core question: Does it make sense to use the app router w/ server actions if the server action is basically forwarding this info to another external API?
Below are my concerns:
Data has to travel through more servers?
For the initial request, if we fetch some data via an external REST API in a server component and pass it down to client components, this isn't a cause for concern as this is basically how the pages router already worked. Ideally, the REST server and the Next.js server are close to each other.
However, the part that's confusing me is what happens when we need to fetch data from the client? Examples I've seen look something like this:
- Fetch initial data in server component using some server function (e.g. getPosts) and pass to client
- Set up react query (or something similar) in the client and initialize with the data from the server
- Refetch with react query using the same "getPosts" server function
Code example:
// File: server-code.ts
"use server"
export async function getPosts() {
// make some fetch request here to the external API and return the data.
}
// File: page.tsx
export default async function HomePage() {
const posts = await getPosts();
return <PostsView posts={posts} />
}
// File: posts-view
"use client"
export default async function PostsView {
const {data, isLoading, refetch} = useQuery({
queryKey: ["posts"],
queryFn: () => getPosts(), // NOTICE THIS IS THE SERVER FUNCTION
}
Notice, when react query needs to refetch, it will fetch using the "getPosts" server function. This means, the client will hit the next js server, then the next.js server will go and hit our API. This seems like far too much, but it's the best DX I've seen for initializing client query functions and keeping it in sync with how the server is processing data.
The same idea applies to basic server actions. Why should I be POSTing to the next.js server if it's just going to forward info over to my external API? This feels like it would be far too slow. I feel like I'm missing out on most of the great app router features becuase I'm using an external API, which begs the question:
Is Next.js App Router worth using if we need an external API (not using route handlers)?