3.6.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 that is 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.
Example: Server-Sent Events (SSE)#
For example, to create an API route that returns server-sent events (SSE), you can set the Content-Type
header to text/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("data: Streaming data...\n\n")15 }, 3000)16 17 req.on("close", () => {18 clearInterval(interval)19 res.end()20 })21 22 req.on("end", () => {23 clearInterval(interval)24 res.end()25 })26}
The writeHead
method accepts two parameters:
- The first parameter is the response's status code.
- The second parameter is an object of key-value pairs to set the response headers.
This API route opens a stream by setting the Content-Type
to text/event-stream
. It then simulates a stream by creating an interval that writes the stream data every three seconds.
Tip: Fetching Stream with JS SDK#
The JS SDK has a fetchStream
method that you can use to fetch data from an API route that returns a stream.
Learn more in the JS SDK documentation.
Do More with Responses#
The MedusaResponse
type is based on Express's Response. Refer to their API reference for other uses of responses.