- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
3.5.3. API Route Response
In this chapter, you'll learn how to send a response in your API route.
Send a JSON Response#
To send a JSON response, use the json
method of the MedusaResponse
object passed as the second parameter of your API route handler.
For example:
This API route returns the following JSON object:
Set Response Status Code#
By default, setting the JSON data using the json
method returns a response with a 200
status code.
To change the status code, use the status
method of the MedusaResponse
object.
For example:
The response of this API route has the status code 201
.
Change Response Content Type#
To return response data other than a JSON object, use the writeHead
method of the MedusaResponse
object. It allows you to set the response headers, including the content type.
For example, to create an API route that returns an event stream:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2 3export const GET = async (4 req: MedusaRequest,5 res: MedusaResponse6) => {7 res.writeHead(200, {8 "Content-Type": "text/event-stream",9 "Cache-Control": "no-cache",10 Connection: "keep-alive",11 })12 13 const interval = setInterval(() => {14 res.write("Streaming data...\n")15 }, 3000)16 17 req.on("end", () => {18 clearInterval(interval)19 res.end()20 })21}
The writeHead
method accepts two parameters:
- The first one is the response's status code.
- The second is an object of key-value pairs to set the headers of the response.
This API route opens a stream by setting the Content-Type
in the header to text/event-stream
. It then simulates a stream by creating an interval that writes the stream data every three seconds.
Do More with Responses#
The MedusaResponse
type is based on Express's Response. Refer to their API reference for other uses of responses.