Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: send user back with the correct type and fix typos #10227

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions docs/authentication/custom-strategies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ At its core a strategy simply takes information from the incoming request and re
Your `authenticate` method should return an object containing a Payload user document and any optional headers that you'd like Payload to set for you when we return a response.

```ts
import type { CollectionConfig } from 'payload'
import type { CollectionConfig, User } from 'payload'

export const Users: CollectionConfig = {
slug: 'users',
Expand All @@ -48,7 +48,7 @@ export const Users: CollectionConfig = {
strategies: [
{
name: 'custom-strategy',
authenticate: ({ payload, headers }) => {
authenticate: async ({ payload, headers }) => {
const usersQuery = await payload.find({
collection: 'users',
where: {
Expand All @@ -61,10 +61,19 @@ export const Users: CollectionConfig = {
},
})

// Send null if no user should be authenticated
if (!usersQuery.docs[0]) return { user: null }

const user: User = {
...usersQuery.docs[0],

// Returned user also needs the collection property
collection: 'users',
}
Comment on lines +67 to +72
Copy link
Member

@r1tsuu r1tsuu Jan 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace spread that introduces copying overhead with mutation:

const user = usersQuery.docs[0] as unknown as User | undefined;
// handle null
user.collection = 'users'

The as cast is needed when using strict: true


return {
// Send the user back to authenticate,
// or send null if no user should be authenticated
user: usersQuery.docs[0] || null,
// Send the user back to authenticate
user,

// Optionally, you can return headers
// that you'd like Payload to set here when
Expand Down