Skip to main content
Skip to main content

Auth Module

The Auth Module is the @medusajs/auth NPM package that provides authentication-related features in your Medusa and Node.js applications.


Features

Authenticate Users

With the Auth Module, authenticate users using their credentials.

const { success, authUser, error } =
await authModuleService.authenticate("emailpass", {
url: req.url,
headers: req.headers,
query: req.query,
body: req.body,
authScope: "admin",
protocol: req.protocol,
} as AuthenticationInput)

if (!success) {
throw new Error(error)
}

// user is authenticated

Third-Party and Social Authentication

The Auth Module supports a variety of authentication methods, such as authenticating with third-party services and social platforms.

// in authentication API route
const { success, authUser, location } =
await authModuleService.authenticate("google", {
url: req.url,
headers: req.headers,
query: req.query,
body: req.body,
authScope: "admin",
protocol: req.protocol,
} as AuthenticationInput)

if (!authUser && location) {
res.redirect(location)
return
}

// in callback API route
const { success, authUser } =
await authModuleService.validateCallback("google", {
url: req.url,
headers: req.headers,
query: req.query,
body: req.body,
authScope: "admin",
protocol: req.protocol,
} as AuthenticationInput)

Configure Auth Module

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

medusa-config.js
const modules = {
// ...
auth: {
resolve: "@medusajs/auth",
options: {
providers: [
// ...
],
},
},
}

Module Options

Refer to this documentation for details on the module's options.


How to Use Auth Module's Service

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

For example:

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

export async function GET(
req: MedusaRequest,
res: MedusaResponse
): Promise<void> {
const authModuleService: IAuthModuleService =
req.scope.resolve(ModuleRegistrationName.AUTH)

res.json({
authUsers: authModuleService.list(),
})
}
Was this section helpful?