Publishable API Keys with Sales Channels

In this document, you’ll learn what publishable API keys are and how to use them with sales channels.

Publishable API Keys with Sales Channels#

A publishable API key, provided by the API Key Module, is a client key scoped to one or more sales channels.

When sending a request to a Store API route, you must pass a publishable API key in the header of the request:

Code
1curl http://localhost:9000/store/products \2  x-publishable-api-key: {your_publishable_api_key}

The Medusa application infers the associated sales channels and ensures that only data relevant to the sales channel are used.


How to Create a Publishable API Key?#

To create a publishable API key, either use the Medusa Admin or the Admin API Routes.


Access Sales Channels in Custom Store API Routes#

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.

For example:

Code
1import { MedusaStoreRequest, MedusaResponse } from "@medusajs/framework/http"2import { getVariantAvailability } from "@medusajs/framework/utils"3
4export async function GET(5  req: MedusaStoreRequest,6  res: MedusaResponse7) {8  const query = req.scope.resolve("query")9  const sales_channel_ids = req.publishable_key_context.sales_channel_ids10
11  res.json({12    sales_channel_id: sales_channel_ids[0],13  })14}

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.

You can then use these IDs based on your business logic. For example, you can retrieve the sales channels' details using Query.

Tip: Notice that the request object's type is MedusaStoreRequest instead of MedusaRequest to ensure the availability of the publishable_key_context property.
Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break