Introduction
Response formatting helps you send data back to the user in a clear and useful way. It makes sure the information looks right and is easy to understand.
Jump into concepts and practice - no test required
Response formatting helps you send data back to the user in a clear and useful way. It makes sure the information looks right and is easy to understand.
export async function GET(request) { return new Response(JSON.stringify({ message: 'Hello' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); }
Response to create a response with body, status, and headers.Content-Type header to tell the client what type of data you send.export async function GET() { return new Response('Hello World', { status: 200, headers: { 'Content-Type': 'text/plain' } }); }
export async function GET() { const data = { name: 'Alice', age: 30 }; return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } }); }
export async function GET() { return new Response(JSON.stringify({ error: 'Not found' }), { status: 404, headers: { 'Content-Type': 'application/json' } }); }
This Next.js API route sends a JSON response with user data. The client will receive the user info as JSON with status 200.
export async function GET() { const user = { id: 1, name: 'John Doe' }; const json = JSON.stringify(user); return new Response(json, { status: 200, headers: { 'Content-Type': 'application/json' } }); }
Always stringify objects before sending in the response body.
Set the correct Content-Type header so browsers and clients know how to handle the data.
You can customize status codes to indicate success or errors.
Response formatting controls how your server sends data back.
Use Response with body, status, and headers for clear communication.
Always set Content-Type to match your data format.
Content-Type header in a Next.js API response?Content-Typeexport async function GET() {
const data = { message: 'Hello' };
return new Response(JSON.stringify(data), {
status: 201,
headers: { 'Content-Type': 'application/json' }
});
}export async function POST() {
const data = { success: true };
return new Response(data, {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}