Skip to content

Commit f911249

Browse files
committed
docs: Add "Getting the payload session" section & improved some other wordings
1 parent 3f1711d commit f911249

File tree

1 file changed

+163
-33
lines changed

1 file changed

+163
-33
lines changed

packages/payload-authjs/README.md

Lines changed: 163 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,25 @@
99

1010
A [Payload CMS 3](https://payloadcms.com) plugin for integrating [Auth.js 5 (beta)](https://authjs.dev).
1111

12-
> ⚠ This plugin and Auth.js is in beta and may have some bugs. Please report any issues you find.
12+
> ⚠ This plugin and Auth.js 5 is in beta and may have some bugs. Please report any issues you find.
13+
14+
# ⚡ How it works
15+
16+
This plugin
17+
18+
- creates a `users` collection in Payload CMS.
19+
- use an custom [Database Adapter](https://authjs.dev/getting-started/database) for Auth.js to store the users in the Payload CMS database.
20+
- use a custom [Auth Strategy](https://payloadcms.com/docs/authentication/custom-strategies) for Payload CMS to retrieve the session from Auth.js.
1321

1422
# ⚙️ Installation / Setup
1523

16-
Install the plugin using any JavaScript package manager like PNPM, NPM, or Yarn:
24+
Install the plugin using any JavaScript package manager such as PNPM, NPM, or Yarn:
1725

1826
```bash
1927
pnpm i payload-authjs
2028
```
2129

22-
Fist of all, setup Auth.js like you would do in a Next.js application. You can follow the [Auth.js guide](https://authjs.dev/getting-started/installation?framework=Next.js).
30+
First of all, this plugin only integrates Auth.js into Payload CMS by getting the user session from Auth.js. It doesn't handle the Auth.js stuff. First, you need to setup Auth.js before you can use this plugin. You can follow the [Auth.js guide](https://authjs.dev/getting-started/installation?framework=Next.js).
2331

2432
> ⚠ Make sure you define your config in a separate file (e.g. `auth.config.ts`) than where you create the NextAuth instance (e.g. `auth.ts`) to avoid circular dependencies. ⚠
2533
@@ -34,7 +42,9 @@ export const authConfig: NextAuthConfig = {
3442
};
3543
```
3644

37-
Wrap your Auth.js configuration with the `withPayload` function before creating the NextAuth instance:
45+
Once you have configured Auth.js, you can integrate it with Payload CMS.
46+
47+
To do this, wrap your Auth.js configuration with the `withPayload` function before creating the NextAuth instance:
3848

3949
```ts
4050
// auth.ts
@@ -50,7 +60,7 @@ export const { handlers, signIn, signOut, auth } = NextAuth(
5060
);
5161
```
5262

53-
Add the `authjsPlugin` in your Payload configuration file:
63+
And add the `authjsPlugin` to your Payload configuration file:
5464

5565
```ts
5666
// payload.config.ts
@@ -68,10 +78,145 @@ export const config = buildConfig({
6878

6979
**And that's it! Now you can sign-in via Auth.js and you are automatically authenticated in Payload CMS. Nice 🎉**
7080

71-
> You don't need to create a collection for users. This plugin automatically creates a collection with the slug `users`.
81+
> _You don't need to create a users collection. This plugin automatically creates a collection with the slug `users`._
7282
7383
---
7484

85+
# 🪄 Getting the payload session
86+
87+
This plugin also provides some utility functions to get the current payload session/user within your Next.js application.
88+
89+
## Server side (`getPayloadSession`)
90+
91+
Instead of using the [`auth`](https://authjs.dev/getting-started/session-management/get-session?framework=next-js) function of Auth.js, you can use the `getPayloadSession` function to get the current session in the server-side code (e.g. in RSC or API routes):
92+
93+
```tsx
94+
// ServerComponentExample.tsx
95+
import { getPayloadSession } from "payload-authjs";
96+
97+
const ServerComponentExample = async () => {
98+
const session = await getPayloadSession();
99+
100+
return (
101+
<>
102+
<h3>Payload CMS User:</h3>
103+
<pre>{JSON.stringify(session?.user)}</pre>
104+
</>
105+
);
106+
};
107+
```
108+
109+
## Client side (`usePayloadSession`)
110+
111+
Instead of using the [`useSession`](https://authjs.dev/getting-started/session-management/get-session?framework=next-js-client) hook of Auth.js, you can use the `usePayloadSession` hook to get the current session in the client-side code:
112+
113+
Before you can use the `usePayloadSession` hook, you need to wrap your app with the `PayloadSessionProvider` on the server-side:
114+
115+
```tsx
116+
// layout.tsx
117+
import { PayloadSessionProvider } from "payload-authjs";
118+
119+
const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
120+
return (
121+
<html lang="en">
122+
<body>
123+
<PayloadSessionProvider>{children}</PayloadSessionProvider>
124+
</body>
125+
</html>
126+
);
127+
};
128+
129+
export default Layout;
130+
```
131+
132+
You are now ready to use the `usePayloadSession` hook in your client-side code:
133+
134+
```tsx
135+
// ClientComponentExample.tsx
136+
"use client";
137+
138+
import { usePayloadSession } from "payload-authjs/client";
139+
140+
export const ClientComponentExample = () => {
141+
const { session } = usePayloadSession();
142+
143+
return (
144+
<>
145+
<h3>Payload CMS User:</h3>
146+
<pre>{JSON.stringify(session?.user)}</pre>
147+
</>
148+
);
149+
};
150+
```
151+
152+
## Within Payload CMS
153+
154+
<details>
155+
<summary>Click to expand</summary>
156+
157+
### Within the Payload admin panel (`useAuth`)
158+
159+
If you want to access the current user in the Payload admin panel e.g. in a custom component. You can use the [`useAuth`](https://payloadcms.com/docs/admin/hooks#useauth) hook from Payload CMS:
160+
161+
```tsx
162+
"use client";
163+
164+
import { Banner, useAuth } from "@payloadcms/ui";
165+
import { type User } from "payload/generated-types";
166+
167+
export const CustomAdminComponent = () => {
168+
const { user } = useAuth<User>();
169+
170+
if (!user) {
171+
return null;
172+
}
173+
174+
return <Banner type="success">Hi, {user.name}</Banner>;
175+
};
176+
```
177+
178+
### Inside access control operations (`req.user`)
179+
180+
Simply use the [`req.user`](https://payloadcms.com/docs/access-control/overview) object to determine the current user:
181+
182+
```ts
183+
const Examples: CollectionConfig = {
184+
slug: "examples",
185+
access: {
186+
read: ({ req: { user } }) => {
187+
return Boolean(user) // <-- Check if the user is authenticated
188+
},
189+
},
190+
fields: [
191+
...
192+
],
193+
};
194+
```
195+
196+
### Inside custom endpoints (`req.user`)
197+
198+
Simply use the [`req.user`](https://payloadcms.com/docs/rest-api/overview#custom-endpoints) object to determine the current user:
199+
200+
```ts
201+
const Examples: CollectionConfig = {
202+
slug: "examples",
203+
fields: [
204+
...
205+
],
206+
endpoints: [
207+
{
208+
method: "get",
209+
path: "/example",
210+
handler: (req) => {
211+
return Response.json(req.user); // <-- Return the user object
212+
},
213+
},
214+
],
215+
};
216+
```
217+
218+
</details>
219+
75220
# 🛠️ Advanced usage / Customization
76221

77222
If you want to customize the users collection, you can create a collection with the slug `users` and add your customizations there.
@@ -89,7 +234,7 @@ const Users: CollectionConfig = {
89234
<details>
90235
<summary>Click to expand</summary>
91236

92-
You can customize the existing fields in the users collection by adding the field to the collection and modifying the field. The fields will be merged together.
237+
You can customize the existing fields in the users collection by adding the field to the collection and modifying the field. The fields are merged together.
93238

94239
```ts
95240
// users.ts
@@ -177,12 +322,12 @@ const authConfig: NextAuthConfig = {
177322
};
178323
```
179324

180-
> Keep in mind that Auth.js doesn't update the user after the first sign-in. If you want to update the user on every sign-in, you can use the `signIn` event. (See [Events](#events))
325+
> Note that Auth.js doesn't update the user after the first sign-in. If you want to update the user on every sign-in, you can use the `signIn` event. (See [Events](#events))
181326
182327
### 2. Virtual fields (jwt session only)
183328

184329
If you are using the Auth.js `jwt` session strategy (it's the default), you can use a [virtual field](https://payloadcms.com/docs/fields/overview#virtual-fields) to add additional data that should not be stored in the database.
185-
This plugin extracts the virtual fields from your Auth.js jwt session and adds them to the user object.
330+
This plugin extracts the virtual fields from your Auth.js jwt session (if available) and adds them to the user object.
186331

187332
For example, you could add a `roles` field to the users collection:
188333

@@ -204,13 +349,16 @@ const Users: CollectionConfig = {
204349
};
205350
```
206351

207-
Next, you need to extend your Auth.js session with your field. You can do this as shown in this example:
352+
This plugin can only get the virtual fields, if **they are included in the Auth.js session**. So you need to extend your Auth.js token and session with your field.
353+
354+
You can do this as shown in this example:
208355

209356
```ts
210357
// auth.config.ts
211358
const authConfig: NextAuthConfig = {
212359
callbacks: {
213360
jwt: ({ token, trigger }) => {
361+
// Add the virtual field to the token only on signIn/signUp (jwt callback will be called multiple times)
214362
if (trigger === "signIn" || trigger === "signUp") {
215363
token.roles = ["example-role"]; // <-- Add your virtual field to the token
216364
}
@@ -227,13 +375,13 @@ const authConfig: NextAuthConfig = {
227375
};
228376
```
229377

230-
At this point, you can implement your own logic to extend the session. E.g. extract from profile, fetch from a server, or something else.
378+
At this point, you can implement your own logic to extend the session. For example extract from profile, fetch from a server, or something else.
231379

232380
_More information about extending your session can be found in the [Auth.js documentation](https://authjs.dev/guides/extending-the-session)._
233381

234-
### Use custom fields
382+
### Using custom fields
235383

236-
Now you could access your custom field, e.g. in the access control operations or somewhere else:
384+
Now you can access your custom field, e.g. in the access control operations or elsewhere:
237385

238386
```ts
239387
const Examples: CollectionConfig = {
@@ -269,7 +417,7 @@ _More information about typescript can be found in the [Auth.js documentation](h
269417

270418
## 🎉 Events
271419

272-
Auth.js emits some [events](https://authjs.dev/reference/nextjs#events) that you can listen to. This plugin extends the events with additional parameters like the `adapter` and `payload` instance.
420+
Auth.js emits some [events](https://authjs.dev/reference/nextjs#events) that you can listen to. This plugin extends the events with additional parameters such as the `adapter` and `payload` instance.
273421

274422
_More information about the events can be found in the [Auth.js documentation](https://authjs.dev/reference/nextjs#events)._
275423

@@ -284,7 +432,7 @@ The following events are available:
284432

285433
### `signIn` Event
286434

287-
The `signIn` event is emitted when a user successfully signs in. For example, you could use this event to update the user's name on every sign-in:
435+
The `signIn` event is fired when a user successfully signs in. For example, you could use this event to update the user's name on every sign-in:
288436

289437
```ts
290438
// auth.ts
@@ -308,21 +456,3 @@ export const { handlers, signIn, signOut, auth } = NextAuth(
308456
}),
309457
);
310458
```
311-
312-
## 📐 Utility functions
313-
314-
This plugin also exports a utility function to get the current payload user in the server-side:
315-
316-
```tsx
317-
// ServerComponentExample.tsx
318-
const ServerComponentExample = async () => {
319-
const payloadUser = await getPayloadUser();
320-
321-
return (
322-
<div>
323-
<h3>Payload CMS User</h3>
324-
<div>{JSON.stringify(payloadUser)}</div>
325-
</div>
326-
);
327-
};
328-
```

0 commit comments

Comments
 (0)