4.2.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:

src/api/custom/route.ts
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2
3export const GET = async (4  req: MedusaRequest,5  res: MedusaResponse6) => {7  res.json({8    message: "Hello, World!",9  })10}

This API route returns the following JSON object:

Code
1{2  "message": "Hello, World!"3}

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:

src/api/custom/route.ts
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2
3export const GET = async (4  req: MedusaRequest,5  res: MedusaResponse6) => {7  res.status(201).json({8    message: "Hello, World!",9  })10}

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:

Code
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:

  1. The first one is the response's status code.
  2. 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.

Was this chapter helpful?
Edit this page