Server Response Object
What is the Response Object?
This is the object that is often abbreviated to res
. This object includes a set of helper methods that can improve developer experience and also increase the speed of creating new API endpoints.
The Server Response Object Helpers
res.status(code)
: This is a function that sets the status code.code:
must be a valid HTTP status code.res.json(body)
: This sends a JSON response.body
must be a serializable object.
res.send(body):
This sends the HTTP response.body
can be astring
, anobject
or aBuffer
res.redirect([status,], path):
This redirects you to a specific path or a URL.status
has to be a valid HTTP status code.If nothing is specified,
status
will default to "307" "Temporary redirect"
Setting the status code of a response
You can set a status code of the response you send back to the client.
Example code:
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
The status code of the response is set to `200` which means `OK`.- It returns a `message` property which has `'Hello from Next.js!'` as its value in the JSON response.
Sending a JSON Response
Like mentioned above, you can send a JSON message back with your response to the client. This response, however, must be a serialized object.
You might want to let the client know the status of the request depending on the result of the requested endpoint.
Example:
export default async function handler(req, res) {
try {
const result = await someAsyncOperation()res.status(200).json({ result })
}
catch (err) {res.status(500).json({ error: 'failed to load data' })}}
JSON response with the status code `200` is sent together with the result of the async operation.
It is contained in a try catch block to handle errors that might occur.
The appropriate status code and error message are caught and sent back to the client.
Sending an HTTP response
This works the same way as sending a JSON response, but the difference is that the response body can be a 'string'
, 'object'
or a 'Buffer'
.
Example:
export default async function handler(req, res) {
try {
const result = await someAsyncOperation()res.status(200).send({ result })
}
catch (err) {res.status(500).send({ error: 'failed to fetch data; })}}
Redirects to a specified path or URL
Let's say you want to redirect your client to a specified path or URL once something changes. A good example can be a form, where you change the path or URL once the form is submitted.
Example:
export default async function handler(req, res) {
const { name, message } = req.body
try {await handleFormInputAsync({ name, message })res.redirect(307, '/')}
catch (err) {res.status(500).send({ error: 'failed to fetch data' })}}
The clients gets redirected to the /
path if the form is successfully submitted.