|
1
|
--- |
|
2
|
products: |
|
3
|
- api key |
|
4
|
--- |
|
5
|
|
|
6
|
import { CodeTabs, CodeTab } from "docs-ui" |
|
7
|
|
|
8
|
export const metadata = { |
|
9
|
title: `Publishable API Keys with Sales Channels`, |
|
10
|
} |
|
11
|
|
|
12
|
# {metadata.title} |
|
13
|
|
|
14
|
In this document, you’ll learn what publishable API keys are and how to use them with sales channels. |
|
15
|
|
|
16
|
## Publishable API Keys with Sales Channels |
|
17
|
|
|
18
|
A publishable API key, provided by the API Key Module, is a client key scoped to one or more sales channels. |
|
19
|
|
|
20
|
When sending a request to a Store API route, you must pass a publishable API key in the header of the request: |
|
21
|
|
|
22
|
```bash |
|
23
|
curl http://localhost:9000/store/products \ |
|
24
|
x-publishable-api-key: {your_publishable_api_key} |
|
25
|
``` |
|
26
|
|
|
27
|
The Medusa application infers the associated sales channels and ensures that only data relevant to the sales channel are used. |
|
28
|
|
|
29
|
--- |
|
30
|
|
|
31
|
## How to Create a Publishable API Key? |
|
32
|
|
|
33
|
To create a publishable API key, either use the [Medusa Admin](!user-guide!/settings/developer/publishable-api-keys) or the [Admin API Routes](!api!/admin#publishable-api-keys). |
|
34
|
|
|
35
|
--- |
|
36
|
|
|
37
|
## Access Sales Channels in Custom Store API Routes |
|
38
|
|
|
39
|
If you create an API route under the `/store` prefix, you can access the sales channels associated with the request's publishable API key using the `publishable_key_context` property of the request object. |
|
40
|
|
|
41
|
For example: |
|
42
|
|
|
43
|
```ts |
|
44
|
import { MedusaStoreRequest, MedusaResponse } from "@medusajs/framework/http" |
|
45
|
import { |
|
46
|
getVariantAvailability, |
|
47
|
ContainerRegistrationKeys, |
|
48
|
} from "@medusajs/framework/utils" |
|
49
|
|
|
50
|
export async function GET( |
|
51
|
req: MedusaStoreRequest, |
|
52
|
res: MedusaResponse |
|
53
|
) { |
|
54
|
const query = req.scope.resolve( |
|
55
|
ContainerRegistrationKeys.QUERY |
|
56
|
) |
|
57
|
const sales_channel_ids = req.publishable_key_context.sales_channel_ids |
|
58
|
|
|
59
|
res.json({ |
|
60
|
sales_channel_id: sales_channel_ids[0], |
|
61
|
}) |
|
62
|
} |
|
63
|
``` |
|
64
|
|
|
65
|
In this example, you retrieve the scope's sales channel IDs using `req.publishable_key_context.sales_channel_ids`, whose value is an array of IDs. |
|
66
|
|
|
67
|
You can then use these IDs based on your business logic. For example, you can retrieve the sales channels' details using [Query](!docs!/learn/fundamentals/query). |
|
68
|
|
|
69
|
<Note title="Tip"> |
|
70
|
|
|
71
|
Notice that the request object's type is `MedusaStoreRequest` instead of `MedusaRequest` to ensure the availability of the `publishable_key_context` property. |
|
72
|
|
|
73
|
</Note> |