Skip to main content
Skip to main content

API Key Module

The API Key Module is the @medusajs/api-key NPM package that provides API-key-related features in your Medusa and Node.js applications.


Features

API Key Types and Management

Store and manage API keys in your store. You can create both publishable and secret API keys for different use cases, such as:

  • Publishable API Key associated with resources like sales channels.
  • Authentication token for admin users to access Admin API Routes.
  • Password reset tokens when a user or customer requests to reset their password.
const pubApiKey = await apiKeyModuleService.create({
title: "Publishable API key",
type: "publishable",
created_by: "user_123",
})

const secretApiKey = await apiKeyModuleService.create({
title: "Authentication Key",
type: "secret",
created_by: "user_123",
})

Token Verification

Verify tokens of secret API keys to authenticate users or actions, such as verifying a password reset token.

const authenticatedToken =
await apiKeyModuleService.authenticate("sk_123")

if (!authenticatedToken) {
console.error("Couldn't verify token")
} else {
console.log("Token verified successfully!")
}

Revoke Keys

Revoke keys to disable their use permenantly.

const revokedKey = await apiKeyModuleService.revoke("apk_1")

Roll API Keys

Roll API keys by revoking a key then re-creating it.

const revokedKey = await apiKeyModuleService.revoke("apk_1")

const newKey = await apiKeyModuleService.create({
title: revokedKey.title,
type: revokedKey.type,
created_by: revokedKey.created_by,
})

Configure API Key Module

After installing the @medusajs/api-key package in your Medusa application, add it to the modules object in medusa-config.js:

medusa-config.js
const modules = {
// ...
apiKey: {
resolve: "@medusajs/api-key",
},
}

How to Use API Key Module's Service

You can use the API Key Module's main service by resolving from the dependency container the resource ModuleRegistrationName.API_KEY imported from @medusajs/modules-sdk.

For example:

import { MedusaRequest, MedusaResponse } from "@medusajs/medusa"
import { IApiKeyModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"

export async function GET(
request: MedusaRequest,
res: MedusaResponse
): Promise<void> {
const apiKeyModuleService: IApiKeyModuleService =
request.scope.resolve(ModuleRegistrationName.API_KEY)

res.json({
api_keys: await apiKeyModuleService.list(),
})
}
Was this section helpful?