Raw
1 import { Table, CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `Authentication in JS SDK`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn about the default authentication setup when using the JS SDK, how to customize it, and how to send authenticated requests to Medusa's APIs.
10
11 ## Default Authentication Settings in JS SDK
12
13 The JS SDK facilitates authentication by storing and managing the necessary authorization headers or sessions for you.
14
15 There are three types of authentication:
16
17 <Table>
18 <Table.Header>
19 <Table.Row>
20 <Table.HeaderCell>
21 Method
22 </Table.HeaderCell>
23 <Table.HeaderCell>
24 Description
25 </Table.HeaderCell>
26 <Table.HeaderCell>
27 When to use
28 </Table.HeaderCell>
29 </Table.Row>
30 </Table.Header>
31 <Table.Body>
32 <Table.Row>
33 <Table.Cell>
34 JWT token (default)
35 </Table.Cell>
36 <Table.Cell>
37 When you log in a user, the JS SDK stores the JWT for you and automatically includes it in the headers of all requests to the Medusa API. This means you don't have to manually set the authorization header for each request. When the user logs out, the SDK clears the stored JWT.
38 </Table.Cell>
39 <Table.Cell>
40 - You need stateless authentication. For example, you're building a mobile storefront with React Native.
41 - Keep in mind: when logging out, the JS SDK clears the token from storage. However, if the user still has access to the token, they can still send authenticated requests.
42 </Table.Cell>
43 </Table.Row>
44 <Table.Row>
45 <Table.Cell>
46 Cookie session
47 </Table.Cell>
48 <Table.Cell>
49 When you log in a user, the JS SDK stores the session cookie for you and automatically includes it in the headers of all requests to the Medusa API. This means you don't have to manually set the authorization header for each request. When the user logs out, the SDK destroys the session cookie using Medusa's API.
50 </Table.Cell>
51 <Table.Cell>
52 - You need stateful authentication. For example, you're building a web storefront with Next.js or customizations in Medusa Admin.
53 - You want to ensure the session is revoked when the user logs out.
54 </Table.Cell>
55 </Table.Row>
56 <Table.Row>
57 <Table.Cell>
58 Secret API Key
59 </Table.Cell>
60 <Table.Cell>
61 Only available for admin users. You pass the API key in the JS SDK configurations, and it's always passed in the headers of all requests to the Medusa API.
62 </Table.Cell>
63 <Table.Cell>
64 - You're authenticating the admin user.
65 - Keep in mind: the API key must be stored securely and not exposed to the client-side code.
66 </Table.Cell>
67 </Table.Row>
68 </Table.Body>
69 </Table>
70
71 ---
72
73 ## JS SDK Authentication Configurations
74
75 The JS SDK provides a set of configurations to customize the authentication method and storage. You can set these configurations when initializing the SDK.
76
77 <Note title="Tip">
78
79 For a full list of JS SDK configurations and their possible values, check out the [JS SDK Overview](../../page.mdx#js-sdk-configurations) documentation.
80
81 </Note>
82
83 ### Authentication Type
84
85 By default, the JS SDK uses JWT token (`jwt`) authentication. You can change the authentication method or type by setting the `auth.type` configuration to `session`.
86
87 For example:
88
89 ```ts
90 import Medusa from "@medusajs/js-sdk"
91
92 export const sdk = new Medusa({
93 // ...
94 auth: {
95 type: "session",
96 },
97 })
98 ```
99
100 To use a secret API key instead, pass it in the `apiKey` configuration instead:
101
102 ```ts
103 import Medusa from "@medusajs/js-sdk"
104
105 export const sdk = new Medusa({
106 // ...
107 apiKey: "your-api-key",
108 })
109 ```
110
111 The provided API key will be passed in the headers of all requests to the Medusa API.
112
113 ### Change JWT Authentication Storage
114
115 By default, the JS SDK stores the JWT token in the `localStorage` under the `medusa_auth_token` key.
116
117 Some environments or use cases may require a different storage method or `localStorage` may not be available. For example, if you're building a mobile app with React Native, you might want to use `AsyncStorage` instead of `localStorage`.
118
119 You can change the storage method by setting the `auth.jwtTokenStorageMethod` configuration to one of the following values:
120
121 <Table>
122 <Table.Header>
123 <Table.Row>
124 <Table.HeaderCell>
125 Value
126 </Table.HeaderCell>
127 <Table.HeaderCell>
128 Description
129 </Table.HeaderCell>
130 </Table.Row>
131 </Table.Header>
132 <Table.Body>
133 <Table.Row>
134 <Table.Cell>
135 `local` (default)
136 </Table.Cell>
137 <Table.Cell>
138 Uses `localStorage` to store the JWT token.
139 </Table.Cell>
140 </Table.Row>
141 <Table.Row>
142 <Table.Cell>
143 `session`
144 </Table.Cell>
145 <Table.Cell>
146 Uses `sessionStorage` to store the JWT token. This means the token will be cleared when the user closes the browser tab or window.
147 </Table.Cell>
148 </Table.Row>
149 <Table.Row>
150 <Table.Cell>
151 `memory`
152 </Table.Cell>
153 <Table.Cell>
154 Uses a memory storage method. This means the token will be cleared when the user refreshes the page or closes the browser tab or window. This is also useful when using the JS SDK in a server-side environment.
155 </Table.Cell>
156 </Table.Row>
157 <Table.Row>
158 <Table.Cell>
159 `custom`
160 </Table.Cell>
161 <Table.Cell>
162 Uses a custom storage method. This means you can provide your own implementation of the storage method. For example, you can use `AsyncStorage` in React Native or any other storage method that fits your use case.
163 </Table.Cell>
164 </Table.Row>
165 <Table.Row>
166 <Table.Cell>
167 `nostore`
168 </Table.Cell>
169 <Table.Cell>
170 Does not store the JWT token. This means you have to manually set the authorization header for each request. This is useful when you want to use a different authentication method or when you're using the JS SDK in a server-side environment.
171 </Table.Cell>
172 </Table.Row>
173 </Table.Body>
174 </Table>
175
176 #### Custom Authentication Storage in JS SDK
177
178 To use a custom storage method, you need to set the `auth.jwtTokenStorageMethod` configuration to `custom` and provide your own implementation of the storage method in the `auth.storage` configuration.
179
180 The object or class passed to `auth.storage` configuration must have the following methods:
181
182 - `setItem`: A function that accepts a key and value to store the JWT token.
183 - `getItem`: A function that accepts a key to retrieve the JWT token.
184 - `removeItem`: A function that accepts a key to remove the JWT token from storage.
185
186 For example, to use `AsyncStorage` in React Native:
187
188 ```ts
189 import AsyncStorage from "@react-native-async-storage/async-storage"
190 import Medusa from "@medusajs/js-sdk"
191
192 let MEDUSA_BACKEND_URL = "http://localhost:9000"
193
194 if (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL) {
195 MEDUSA_BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
196 }
197
198 export const sdk = new Medusa({
199 baseUrl: MEDUSA_BACKEND_URL,
200 debug: process.env.NODE_ENV === "development",
201 publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
202 auth: {
203 type: "jwt",
204 jwtTokenStorageMethod: "custom",
205 storage: AsyncStorage,
206 },
207 })
208 ```
209
210 In this example, you specify the `jwtTokenStorageMethod` as `custom` and set the `storage` configuration to `AsyncStorage`. This way, the JS SDK will use `AsyncStorage` to store and manage the JWT token instead of `localStorage`.
211
212 ### Change Cookie Session Credentials Options
213
214 By default, if you set the `auth.type` configuration in the JS SDK to `session`, the JS SDK will pass the `credentials: include` option in the underlying [fetch requests](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#including_credentials).
215
216 However, some platforms or environments may not support passing this option. For example, if you're using the JS SDK in a server-side environment or a mobile app, you might want to set the `credentials` option to `same-origin` or `omit`.
217
218 You can change the `credentials` option by setting the `auth.fetchCredentials` configuration to one of the following values:
219
220 <Table>
221 <Table.Header>
222 <Table.Row>
223 <Table.HeaderCell>
224 Value
225 </Table.HeaderCell>
226 <Table.HeaderCell>
227 Description
228 </Table.HeaderCell>
229 </Table.Row>
230 </Table.Header>
231 <Table.Body>
232 <Table.Row>
233 <Table.Cell>
234 `include` (default)
235 </Table.Cell>
236 <Table.Cell>
237 Passes the `credentials: include` option in the fetch requests. This means the JS SDK will include cookies and authorization headers in the requests to the Medusa API.
238 </Table.Cell>
239 </Table.Row>
240 <Table.Row>
241 <Table.Cell>
242 `same-origin`
243 </Table.Cell>
244 <Table.Cell>
245 Passes the `credentials: same-origin` option in the fetch requests. This means the JS SDK will include cookies and authorization headers in the requests to the Medusa API only if the request is made to the same origin as the current page.
246 </Table.Cell>
247 </Table.Row>
248 <Table.Row>
249 <Table.Cell>
250 `omit`
251 </Table.Cell>
252 <Table.Cell>
253 Passes the `credentials: omit` option in the fetch requests. This means the JS SDK will not include cookies or authorization headers in the requests to the Medusa API.
254 </Table.Cell>
255 </Table.Row>
256 </Table.Body>
257 </Table>
258
259 For example:
260
261 ```ts
262 import Medusa from "@medusajs/js-sdk"
263
264 export const sdk = new Medusa({
265 // ...
266 auth: {
267 type: "session",
268 fetchCredentials: "same-origin",
269 },
270 })
271 ```
272
273 In this example, you set the `fetchCredentials` configuration to `same-origin`, which means the JS SDK will include cookies and authorization headers in the requests to the Medusa API only if the request is made to the same origin as the current page.
274
275 ---
276
277 ## Sending Authenticated Requests in JS SDK
278
279 <Note>
280
281 If you're using an API key for authentication, you don't need to log in the user.
282
283 </Note>
284
285 The JS SDK has an `auth.login` method that allows you to login admin users, customers, or any [actor type](../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx) with any [auth provider](../../../commerce-modules/auth/auth-providers/page.mdx).
286
287 Not only does this method log in the user, but it also stores the JWT token or session cookie for you and automatically includes it in the headers of all requests to the Medusa API. This means you don't have to manually set the authorization header for each request.
288
289 For example:
290
291 <CodeTabs group="auth-actor-type">
292 <CodeTab label="Admin User" value="admin">
293
294 ```ts
295 sdk.auth.login("user", "emailpass", {
296 email,
297 password,
298 })
299 .then((data) => {
300 if (typeof data === "object" && data.location){
301 // authentication requires more actions
302 }
303 // user is authenticated
304 })
305 .catch((error) => {
306 // authentication failed
307 })
308 ```
309
310 </CodeTab>
311 <CodeTab label="Customer" value="customer">
312
313 ```ts
314 sdk.auth.login("customer", "emailpass", {
315 email,
316 password,
317 })
318 .then((data) => {
319 if (typeof data === "object" && data.location){
320 // authentication requires more actions
321 }
322 // customer is authenticated
323 })
324 .catch((error) => {
325 // authentication failed
326 })
327 ```
328
329 </CodeTab>
330 <CodeTab label="Custom" value="custom">
331
332 ```ts
333 sdk.auth.login("manager", "emailpass", {
334 email,
335 password,
336 })
337 .then((data) => {
338 if (typeof data === "object" && data.location){
339 // authentication requires more actions
340 }
341 // manager is authenticated
342 })
343 .catch((error) => {
344 // authentication failed
345 })
346 ```
347
348 </CodeTab>
349 </CodeTabs>
350
351 In this example, you call the `sdk.auth.login` method passing it the actor type (for example, `user`), the provider (`emailpass`), and the credentials.
352
353 If the authentication is successful, there are three types of returned data:
354
355 - An object with a `location` property: This means the authentication requires more actions, which happens when using third-party authentication providers, such as [Google](../../../commerce-modules/auth/auth-providers/google/page.mdx). In that case, you need to redirect the customer to the location to complete their authentication.
356 - Refer to the [Third-Party Login in Storefront](../../../storefront-development/customers/third-party-login/page.mdx) guide for an example implementation.
357 - An object with `verification_required: true`: This means the authentication requires email verification before a token can be issued. The object includes verification details like expiry time. Verification is only required if the `require_verification` option is enabled in the [Emailpass Auth Module Provider](../../../commerce-modules/auth/auth-providers/emailpass/page.mdx).
358 - A string: This means the authentication was successful, and the user is logged in. The JS SDK automatically stores the JWT token or session cookie for you and includes it in the headers of all requests to the Medusa API. All requests you send afterwards will be authenticated with the stored token or session cookie.
359
360 If the authentication fails, the `catch` block will be executed, and you can handle the error accordingly.
361
362 You can learn more about this method in the [auth.login reference](/references/js-sdk/auth/login).
363
364 ### Manually Set JWT Token
365
366 If you need to set the JWT token manually, you can use the `sdk.client.setToken` method. All subsequent requests will be authenticated with the provided token.
367
368 For example:
369
370 ```ts
371 sdk.client.setToken("your-jwt-token")
372
373 // all requests sent after this will be authenticated with the provided token
374 ```
375
376 You can also clear the token manually as explained in the [Manually Clearing JWT Token](#manually-clearing-jwt-token) section.
377
378 ---
379
380 ## List Available Auth Providers
381
382 The JS SDK provides a `sdk.auth.listProviders` method to retrieve the auth providers configured for a given actor type. This is useful for building a dynamic login UI that renders the correct options (for example, an email/password form or "Continue with …" redirect buttons) based on the available providers.
383
384 For example:
385
386 ```ts
387 const { providers } = await sdk.auth.listProviders("user")
388
389 for (const provider of providers) {
390 if (provider.flow === "redirect") {
391 // render a "Continue with {provider.display_name}" button
392 } else {
393 // render an email/password form
394 }
395 }
396 ```
397
398 Each provider object contains:
399
400 - `id`: The registered instance ID used in authentication routes (for example, `okta`).
401 - `identifier`: The provider's static type (for example, `oidc` or `emailpass`).
402 - `display_name`: The name to show in the UI.
403 - `flow`: Either `"credentials"` (the user submits credentials directly) or `"redirect"` (the user is redirected to the provider).
404
405 ---
406
407 ## Logout in JS SDK
408
409 <Note>
410
411 If you're using an API key for authentication, you can't log out the user. You'll have to unset the API key in the JS SDK configurations.
412
413 </Note>
414
415 The JS SDK has an `auth.logout` method that allows you to log out the currently authenticated user.
416
417 If the JS SDK's authentication type is `jwt`, the method will only clear the stored JWT token from the local storage. If the authentication type is `session`, the method will destroy the session cookie using Medusa's `/auth/session` API route.
418
419 Any request sent after logging out will not be authenticated, and you will need to log in again to authenticate the user.
420
421 For example:
422
423 ```ts
424 sdk.auth.logout()
425 .then(() => {
426 // user is logged out
427 })
428 ```
429
430 You can learn more about this method in the [auth.logout reference](/references/js-sdk/auth/logout).
431
432 ### Manually Clearing JWT Token
433
434 If you need to clear the JWT token manually, you can use the `sdk.client.clearToken` method. This will remove the token from the local storage and all subsequent requests will not be authenticated.
435
436 For example:
437
438 ```ts
439 sdk.client.clearToken()
440
441 // all requests sent after this will not be authenticated
442 ```