CosmosDb Adapter
Resources
Setup
Installation
npm install @auth/cosmosdb-adapter
Environment Variables
AUTH_COSMOSDB_COSMOSACCOUNT=SomeAccount
AUTH_COSMOSDB_ENDPOINT=https://$AUTH_COSMOSDB_COSMOSACCOUNT.documents.azure.com
AUTH_COSMOSDB_DATABASE=SomeDatabase
AUTH_COSMOSDB_CONTAINER=SomeContainer
AUTH_COSMOSDB_KEY=longRandomKey
Partition Key Strategies
The adapter supports 4 different approaches to partiion keys:
- Default Strategy - Assumes that the partition key is one of the columns included in the data. For e.g. you can use this if you have the partition key set to the Id column.
- Same As Id Strategy - Populates a separate column with the same value of the Id of the record.
- Same As Data Type Strategy - Populates a separate column with the same value of the Data Type of the record.
- Hardcoded Partition Key - Populates a separate column with a hardcoded value. You can use this if for e.g. you have a multi tenant container with data partitioned on a tenant column.
The strategies are configured as follows:
Default Strategy
const adapter = CosmosDbAdapter(container)
Same As Id Strategy
const pc = {
partitionKey: "partitionKeyColumnName",
partitionKeyStrategy: CosmosDbPartitionStrategy.SameAsId,
} as CosmosDbPartitionConfiguration
const adapter = CosmosDbAdapter(container, pc)
Same As Data Type Strategy
const pc = {
partitionKey: "partitionKeyColumnName",
partitionKeyStrategy: CosmosDbPartitionStrategy.SameAsDataType,
} as CosmosDbPartitionConfiguration
const adapter = CosmosDbAdapter(container, pc)
Hardcoded Value Strategy
const pc = {
partitionKey: "partitionKeyColumnName",
partitionKeyStrategy: CosmosDbPartitionStrategy.HardCodedValue,
hardCodedValue: "HardcodedPartitionKeyValue",
} as CosmosDbPartitionConfiguration
const adapter = CosmosDbAdapter(container, pc)
Configuration
- Setup
auth
as in the example below.
./auth.ts
import NextAuth, { type AuthConfig } from "next-auth"
import { CosmosDbAdapter } from "@auth/cosmosdb-adapter"
import { CosmosClient } from "@azure/cosmos"
const endpoint = process.env.AUTH_COSMOSDB_ENDPOINT
const key = process.env.AUTH_COSMOSDB_KEY
const client = new CosmosClient({ endpoint, key })
const database = client.database(process.env.AUTH_COSMOSDB_DATABASE)
const container = database.container(process.env.AUTH_COSMOSDB_CONTAINER)
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [],
adapter: CosmosDbAdapter(container),
} satisfies AuthConfig)