1 export const metadata = {
2 title: `${pageNumber} API Route Response`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you'll learn how to send a response in your API route.
8
9 ## Send a JSON Response
10
11 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.
12
13 For example:
14
15 export const jsonHighlights = [
16 ["7", "json", "Return a JSON object."]
17 ]
18
19 ```ts title="src/api/custom/route.ts" highlights={jsonHighlights}
20 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
21
22 export const GET = async (
23 req: MedusaRequest,
24 res: MedusaResponse
25 ) => {
26 res.json({
27 message: "Hello, World!",
28 })
29 }
30 ```
31
32 This API route returns the following JSON object:
33
34 ```json
35 {
36 "message": "Hello, World!"
37 }
38 ```
39
40 ---
41
42 ## Set Response Status Code
43
44 By default, setting the JSON data using the `json` method returns a response with a `200` status code.
45
46 To change the status code, use the `status` method of the `MedusaResponse` object.
47
48 For example:
49
50 export const statusHighlight = [
51 ["7", "status", "Set the response code to `201`."]
52 ]
53
54 ```ts title="src/api/custom/route.ts" highlights={statusHighlight}
55 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
56
57 export const GET = async (
58 req: MedusaRequest,
59 res: MedusaResponse
60 ) => {
61 res.status(200).json({
62 message: "Hello, World!",
63 })
64 }
65 ```
66
67 The response of this API route has the status code `201`.
68
69 ---
70
71 ## Change Response Content Type
72
73 To return response data other than a JSON object, you can either use the `set`, `setHeader`, or `writeHead` methods of the `MedusaResponse` object. They allow you to set the response headers, including the content type.
74
75 ### Example: Return PDF File
76
77 To create an API route that returns a PDF file, you can set the `Content-Type` header to `application/pdf`:
78
79 ```ts title="src/api/custom/route.ts"
80 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
81
82 export const GET = async (
83 req: MedusaRequest,
84 res: MedusaResponse
85 ) => {
86 // assuming you have the PDF file as buffer
87 res.set({
88 "Content-Type": "application/pdf",
89 "Content-Disposition": `attachment; filename="invoice-${id}.pdf"`,
90 "Content-Length": buffer.length,
91 })
92 res.send(buffer)
93 }
94 ```
95
96 The `set` method allows you to set multiple headers at once. It accepts an object of key-value header pairs.
97
98 ### Example: Return XML Content
99
100 To create an API route that returns XML content, you can set the `Content-Type` header to `application/xml`:
101
102 ```ts title="src/api/custom/route.ts"
103 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
104
105 export const GET = async (
106 req: MedusaRequest,
107 res: MedusaResponse
108 ) => {
109 // Assuming you have XML string
110 res.set({
111 "Content-Type": "application/xml; charset=utf-8",
112 })
113 res.send(xmlString)
114 }
115 ```
116
117 ### Example: Server-Sent Events (SSE)
118
119 To create an API route that returns server-sent events (SSE), you can set the `Content-Type` header to `text/event-stream`:
120
121 export const streamHighlights = [
122 ["7", "writeHead", "Set the response's headers."],
123 ["7", "200", "Set the status code."],
124 ["8", `"Content-Type"`, "Set the response's content type."],
125 ["13", "interval", "Simulate stream data using an interval."],
126 ["14", "write", "Write stream data."],
127 ["17", "on", "Stop the stream when the request is terminated."]
128 ]
129
130 ```ts highlights={streamHighlights}
131 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
132
133 export const GET = async (
134 req: MedusaRequest,
135 res: MedusaResponse
136 ) => {
137 res.writeHead(200, {
138 "Content-Type": "text/event-stream",
139 "Cache-Control": "no-cache",
140 Connection: "keep-alive",
141 })
142
143 const interval = setInterval(() => {
144 res.write("data: Streaming data...\n\n")
145 }, 3000)
146
147 req.on("close", () => {
148 clearInterval(interval)
149 res.end()
150 })
151
152 req.on("end", () => {
153 clearInterval(interval)
154 res.end()
155 })
156 }
157 ```
158
159 The `writeHead` method accepts two parameters:
160
161 1. The first parameter is the response's status code.
162 2. The second parameter is an object of key-value pairs to set the response headers.
163
164 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.
165
166 #### Tip: Fetching Stream with JS SDK
167
168 The JS SDK has a `fetchStream` method that you can use to fetch data from an API route that returns a stream.
169
170 Learn more in the [JS SDK](!resources!/js-sdk) documentation.
171
172 ---
173
174 ## Do More with Responses
175
176 The `MedusaResponse` type is based on [Express's Response](https://expressjs.com/en/api.html#res). Refer to their API reference for other uses of responses.