The fetch function works much as it does in the browser, but using it in a server component lets you take advantage of the server environment.
For example, you can
Server components can access client cookies through Next.js's built-in cookies() API.
For example, retrieve a signed-in user's information from a cookie and forward it with a request.
import { cookies } from 'next/headers';const cookieStore = cookies();const token = cookieStore.get('token');const res = await fetch('https://api.example.com/user', { headers: { Authorization: `Bearer ${token?.value}`, },});
This is useful for handling a user's authentication information securely on the server.
inside app/api/.
For example, create an API that retrieves user information as follows.
// app/api/user/route.tsimport { NextResponse } from 'next/server';export async function GET() { const res = await fetch('https://jsonplaceholder.typicode.com/users/1'); const user = await res.json(); return NextResponse.json(user);}
A request to /api/user will now receive JSON data from the API.
Route handlers can implement individual functions for methods such as GET, POST, PUT, and DELETE, and can work usefully alongside server actions.
We have learned to customize Next.js fetch requests and use cache invalidation to manage data flexibly.
We also saw how route handlers enable an API structure that brings frontend and backend together.
The next part
brings everything together
and compares which strategies work best in different situations.