Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Response Helpers in NextJS

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

javascript

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

javascript

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

javascript

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

javascript

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

javascript

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

javascript

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

javascript

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

javascript

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

javascript

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

HelperUsageExample
res.json(data)Send JSON responsesres.json({ message: "OK" })
res.status(code)Set HTTP statusres.status(404).json({ error: "Not Found" })
res.redirect(url)Redirect usersres.redirect(302, "/home")
res.setHeader(name, value)Set custom headersres.setHeader("Cache-Control", "max-age=3600")
res.send(data)Send plain textres.send("Hello")
res.write(data)Stream responsesres.write("Loading...")

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql