Skip to content

Subject

Reference doc for creating subjects.

Subjects are what the access token generated at the end of the auth flow will map to. Under the hood, the access token is a JWT that contains this data.

Define subjects

subjects.ts
import { object, string } from "valibot"
const subjects = createSubjects({
user: object({
userID: string()
})
})

We are using valibot here. You can use any validation library that’s following the standard-schema specification.

You can start with one subject. Later you can add more for different types of users.

Set the subjects

Then you can pass it to the issuer.

issuer.ts
import { subjects } from "./subjects"
const app = issuer({
providers: { ... },
subjects,
// ...
})

Add the subject payload

When your user completes the flow, you can add the subject payload in the success callback.

issuer.ts
const app = issuer({
providers: { ... },
subjects,
async success(ctx, value) {
let userID
if (value.provider === "password") {
console.log(value.email)
userID = ... // lookup user or create them
}
return ctx.subject("user", {
userID
})
},
// ...
})

Here we are looking up the userID from our database and adding it to the subject payload.

Since these will be stored in the access token, you should avoid storing information that’ll change often. For example, if you store the user’s username, you’ll need to revoke the access token when the user changes their username.

Decode the subject

Now when your user logs in, you can use the OpenAuth client to decode the subject. For example, in our SSR app we can do the following.

app/page.tsx
import { subjects } from "../subjects"
const verified = await client.verify(subjects, cookies.get("access_token")!)
console.log(verified.subject.properties.userID)

All this is typesafe based on the shape of the subjects you defined.


Methods

createSubjects

createSubjects(types)

Parameters

Returns SubjectSchema

Create a subject schema.

const subjects = createSubjects({
user: object({
userID: string()
}),
admin: object({
workspaceID: string()
})
})

This is using valibot to define the shape of the subjects. You can use any validation library that’s following the standard-schema specification.

SubjectSchema

Type Record<string, v1.StandardSchema>

Subject schema is a map of types that are used to define the subjects.