1 import { CodeTabs, CodeTab, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Localization in API Routes`,
5 keywords: ["translation api-routes"]
6 }
7
8 # {metadata.title}
9
10 In this chapter, you'll learn how to handle localization in API routes of your Medusa application to serve content in different languages.
11
12 <Prerequisites
13 items={[
14 {
15 text: "Medusa v2.12.4 or later",
16 link: "https://github.com/medusajs/medusa/releases/tag/v2.12.4"
17 },
18 {
19 text: "Translation Module Configured",
20 link: "!resources!/commerce-modules/translation#configure-translation-module",
21 },
22 ]}
23 />
24
25 ## Overview
26
27 Localization in API routes allows you to serve translated content based on the user's preferred language. The Medusa application provides built-in support for handling locale information in API requests and retrieving localized data.
28
29 When a locale is specified in a request, you can use it to retrieve translated versions of your data models' fields, providing a seamless multilingual experience for your users.
30
31 Learn more about translation, how to manage translations, and how to translate custom data models in the [Translation Module documentation](!resources!/commerce-modules/translation).
32
33 ---
34
35 ## Routes with Localization Enabled by Default
36
37 The Medusa application automatically applies the `applyLocale` middleware to all routes under the `/store` prefix. This makes `req.locale` available in every store route handler, and it allows your custom store routes to read the locale without additional middleware configuration.
38
39 However, applying the locale middleware does not mean every route translates its response automatically. Translation only happens when the route handler (or an underlying helper) resolves the locale and retrieves the appropriate translations. In Medusa's built-in store routes, translation is applied to the following routes:
40
41 - `/store/products` and `/store/products/:id`: product fields such as `title` and `description`
42 - `/store/product-variants` and `/store/product-variants/:id`: product variant fields
43 - `/store/product-categories` and `/store/product-categories/:id`: product category fields
44 - `/store/collections` and `/store/collections/:id`: product collection fields
45 - `/store/product-types` and `/store/product-types/:id`: product type fields
46 - `/store/product-tags` and `/store/product-tags/:id`: product tag fields
47
48 Other built-in store routes (including `/store/carts/:id`, `/store/customers/me`, and `/store/orders/:id`) receive the locale header but do not retrieve the translated content. Fields on data models reached through those routes, including custom models linked to their records, are returned untranslated even when `x-medusa-locale` is set.
49
50 <Note>
51
52 If you need translated fields on a model that is fetched through a non-translating route (for example, a custom model linked to a cart or order), create a custom store route that queries the model directly and [applies the translations](!resources!/commerce-modules/translation/custom-data-models).
53
54 </Note>
55
56 Refer to the [Translation Module](!resources!/commerce-modules/translation#supported-module-translations) documentation for a list of supported core data models with localization support.
57
58 ### Apply Localization to Custom Routes
59
60 If you're creating custom API routes outside the `/store` prefix, you must manually apply the `applyLocale` [middleware](../middlewares/page.mdx) to enable localization support.
61
62 To apply the `applyLocale` middleware to all HTTP methods for a route, add it to the `src/api/middlewares.ts` file:
63
64 export const allMethodsHighlights = [
65 ["7", "applyLocale", "Apply the middleware to the route"],
66 ]
67
68 ```ts title="src/api/middlewares.ts" highlights={allMethodsHighlights}
69 import { applyLocale, defineMiddlewares } from "@medusajs/framework/http"
70
71 export default defineMiddlewares({
72 routes: [
73 {
74 matcher: "/custom*",
75 middlewares: [applyLocale],
76 },
77 ],
78 })
79 ```
80
81 This applies the `applyLocale` middleware to all routes matching `/custom*`, regardless of the HTTP method.
82
83 Alternatively, you can apply the middleware only to specific HTTP methods using the `method` property:
84
85 export const specificMethodHighlights = [
86 ["7", "method", "Apply the middleware only to `GET` requests"],
87 ]
88
89 ```ts title="src/api/middlewares.ts" highlights={specificMethodHighlights}
90 import { applyLocale, defineMiddlewares } from "@medusajs/framework/http"
91
92 export default defineMiddlewares({
93 routes: [
94 {
95 matcher: "/custom*",
96 method: ["GET"],
97 middlewares: [applyLocale],
98 },
99 ],
100 })
101 ```
102
103 <Note title="Tip">
104
105 Learn more about middlewares in the [Middlewares](../middlewares/page.mdx) chapter.
106
107 </Note>
108
109 ---
110
111 ## How to Pass Locale in API Requests
112
113 You can pass the locale in API requests to routes that support localization using either of the following methods:
114
115 1. The `locale` query parameter
116 2. The `x-medusa-locale` request header
117
118 The query parameter takes priority over the header if both are provided.
119
120 The locale must follow the [IETF BCP 47 standard](https://gist.github.com/typpo/b2b828a35e683b9bf8db91b5404f1bd1), such as `en-US` for English (United States) or `fr-FR` for French (France).
121
122 <Note title="Using the JS SDK?">
123
124 Refer to the [JS SDK reference](!resources!/js-sdk#localization-with-js-sdk) for details on how to pass locale.
125
126 </Note>
127
128 For example:
129
130 <CodeTabs group="localization">
131 <CodeTab label="Query Parameter" value="query-param">
132
133 ```bash
134 curl "http://localhost:9000/store/products?locale=fr-FR" \
135 -H 'x-publishable-api-key: {your_publishable_api_key}'
136 ```
137
138 </CodeTab>
139 <CodeTab label="Header" value="header">
140
141 ```bash
142 curl "http://localhost:9000/store/products" \
143 -H 'x-publishable-api-key: {your_publishable_api_key}' \
144 -H 'x-medusa-locale: fr-FR'
145 ```
146
147 </CodeTab>
148 </CodeTabs>
149
150 The above examples retrieve products with their fields translated to French (France) if translations are available. If no translations exist for the requested locale, the original content stored in the data model is returned.
151
152 <Note>
153
154 Store API routes require a publishable API key in the request header. Learn more in the [Store API reference](!api!/store/publishable-api-key).
155
156 </Note>
157
158 ---
159
160 ## Access Request Locale in API Routes
161
162 After applying the `applyLocale` middleware, you can access the request's locale from the `locale` property of the `MedusaRequest` object.
163
164 For example:
165
166 export const accessLocaleHighlights = [
167 ["10", "req.locale", "Access the request's locale"],
168 ]
169
170 ```ts title="src/api/custom/route.ts" highlights={accessLocaleHighlights}
171 import type {
172 MedusaRequest,
173 MedusaResponse,
174 } from "@medusajs/framework/http"
175
176 export const GET = async (
177 req: MedusaRequest,
178 res: MedusaResponse
179 ) => {
180 const locale = req.locale
181
182 // use locale to retrieve localized data...
183 }
184 ```
185
186 The `req.locale` property contains the locale value from either the query parameter or the request header. If no locale is specified in the request, `req.locale` is `undefined`.
187
188 ### Retrieve Localized Data with Query
189
190 To retrieve data models with translated fields, pass the `locale` property in the second parameter object of [Query](/learn/fundamentals/query) when querying your data.
191
192 For example, to retrieve products with translated names and descriptions:
193
194 export const queryHighlights = [
195 ["17", "locale", "Pass the request locale to retrieve localized data"],
196 ]
197
198 ```ts title="src/api/store/products/route.ts" highlights={queryHighlights}
199 import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
200 import {
201 ContainerRegistrationKeys,
202 } from "@medusajs/framework/utils"
203
204 export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
205 const query = req.scope.resolve(
206 ContainerRegistrationKeys.QUERY
207 )
208
209 const { data: products } = await query.graph(
210 {
211 entity: "product",
212 fields: ["id", "title", "description"],
213 },
214 {
215 locale: req.locale,
216 }
217 )
218
219 res.json({ products })
220 }
221 ```
222
223 In this example, the products are retrieved with their `title` and `description` fields translated to the locale specified in the request.
224
225 Learn more in the [Query](../../query/page.mdx#retrieve-localized-data) chapter.
226
227 ### Retrieve Localized Data for Custom Models
228
229 You can also retrieve localized data for custom data models. Learn more in the [Translate Custom Data Models](!resources!/commerce-modules/translation/custom-data-models) guide.