Response Helpers in NextJS
⚡ Response Helpers in Next.js
Next.js provides Response Helpers in API routes (pages/api/) and middleware to handle HTTP responses efficiently. These helpers make it easy to send JSON responses, set headers, manage redirects, and handle errors.
📌 1. Sending JSON Responses (res.json())
Use res.json() to send structured JSON data in API routes.
🔹 Example: Basic JSON Response
export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js API!" });}
✅ Sends a JSON response with status 200 OK
📌 2. Setting HTTP Status Codes (res.status())
You can set custom HTTP status codes using res.status().
🔹 Example: Handling Success & Errors
export default function handler(req, res) { if (req.method !== "GET") { return res.status(405).json({ error: "Method Not Allowed" }); // 405 } res.status(200).json({ message: "Success" });}
✅ Returns 405 Method Not Allowed for non-GET requests
✅ Returns 200 OK for successful GET requests
📌 3. Redirecting Users (res.redirect())
Redirect users from API routes using res.redirect().
🔹 Example: Redirect to Another Page
export default function handler(req, res) { res.redirect(302, "/new-page");}
✅ Redirects the user to /new-page (Temporary Redirect: 302)
📌 4. Setting Custom Headers (res.setHeader())
Use res.setHeader() to add custom headers.
🔹 Example: Caching & Security Headers
export default function handler(req, res) { res.setHeader("Cache-Control", "s-maxage=3600, stale-while-revalidate"); res.setHeader("X-Custom-Header", "NextJS"); res.status(200).json({ message: "Headers Set" });}
✅ Sets cache & custom headers for better performance
📌 5. Sending Plain Text Responses (res.send())
Use res.send() to return raw text instead of JSON.
🔹 Example: Sending a Simple Message
export default function handler(req, res) { res.status(200).send("Hello, Next.js!");}
✅ Useful for API responses that don't need JSON
📌 6. Handling Errors (try/catch)
Use error handling to gracefully respond to failures.
🔹 Example: Handling API Errors
export default async function handler(req, res) { try { const response = await fetch("https://api.example.com/data"); if (!response.ok) throw new Error("Failed to fetch data"); const data = await response.json(); res.status(200).json(data); } catch (error) { res.status(500).json({ error: error.message }); }}
✅ Returns 500 Internal Server Error if the API request fails
📌 7. Streaming Responses (res.write())
Stream large responses using res.write() and res.end().
🔹 Example: Streaming Response
export default function handler(req, res) { res.setHeader("Content-Type", "text/plain"); res.write("Chunk 1\n"); res.write("Chunk 2\n"); res.end("Done\n");}
✅ Useful for streaming large data sets
📌 8. Returning HTML Responses (res.send())
Send raw HTML content as a response.
🔹 Example: Returning HTML
export default function handler(req, res) { res.setHeader("Content-Type", "text/html"); res.send("<h1>Welcome to Next.js</h1>");}
✅ Useful for generating server-side rendered HTML
📌 9. Response Helpers in Middleware (app/middleware.js)
You can modify responses inside middleware before reaching a page.
🔹 Example: Redirect Users in Middleware
import { NextResponse } from "next/server";export function middleware(req) { if (!req.cookies.token) { return NextResponse.redirect(new URL("/login", req.url)); }}
✅ Redirects users to /login if they are not authenticated
🚀 Summary: Response Helpers in Next.js
| Helper | Usage | Example |
|---|---|---|
res.json(data) | Send JSON responses | res.json({ message: "OK" }) |
res.status(code) | Set HTTP status | res.status(404).json({ error: "Not Found" }) |
res.redirect(url) | Redirect users | res.redirect(302, "/home") |
res.setHeader(name, value) | Set custom headers | res.setHeader("Cache-Control", "max-age=3600") |
res.send(data) | Send plain text | res.send("Hello") |
res.write(data) | Stream responses | res.write("Loading...") |