Skip to content

Commit bf0680a

Browse files
committed
feat: Fist implementation
1 parent 1e28d29 commit bf0680a

30 files changed

+1314
-227
lines changed

README.md

Lines changed: 52 additions & 199 deletions
Original file line numberDiff line numberDiff line change
@@ -1,226 +1,79 @@
1-
# Payload Plugin Template
1+
# Payload CMS plugin for Auth.js
22

3-
A template repo to create a [Payload CMS](https://payloadcms.com) plugin.
3+
A [Payload CMS 3 (beta)](https://payloadcms.com) plugin for integrating [Auth.js 5 (beta)](https://authjs.dev).
44

5-
Payload is built with a robust infrastructure intended to support Plugins with ease. This provides a simple, modular, and reusable way for developers to extend the core capabilities of Payload.
5+
### Installation
66

7-
To build your own Payload plugin, all you need is:
8-
9-
* An understanding of the basic Payload concepts
10-
* And some JavaScript/Typescript experience
11-
12-
## Background
13-
14-
Here is a short recap on how to integrate plugins with Payload, to learn more visit the [plugin overview page](https://payloadcms.com/docs/plugins/overview).
7+
Install the plugin using any JavaScript package manager like Yarn, NPM, or PNPM:
8+
9+
```bash
10+
pnpm i payload-authjs
11+
```
1512

16-
### How to install a plugin
13+
### Basic Usage
1714

18-
To install any plugin, simply add it to your payload.config() in the Plugin array.
15+
Install the `authjsPlugin` in your Payload configuration file:
1916

2017
```ts
21-
import samplePlugin from 'sample-plugin';
18+
// payload.config.ts
19+
import { authjsPlugin } from "payload-authjs";
20+
import { authConfig } from "./auth.config";
2221

2322
export const config = buildConfig({
2423
plugins: [
25-
// You can pass options to the plugin
26-
samplePlugin({
27-
enabled: true,
24+
authjsPlugin({
25+
authjsConfig: authConfig,
2826
}),
2927
]
3028
});
3129
```
3230

33-
### Initialization
34-
35-
The initialization process goes in the following order:
36-
37-
1. Incoming config is validated
38-
2. **Plugins execute**
39-
3. Default options are integrated
40-
4. Sanitization cleans and validates data
41-
5. Final config gets initialized
42-
43-
## Building the Plugin
44-
45-
When you build a plugin, you are purely building a feature for your project and then abstracting it outside of the project.
46-
47-
### Template Files
48-
49-
In the [payload-plugin-template](https://github.com/payloadcms/payload-plugin-template), you will see a common file structure that is used across all plugins:
50-
51-
1. root folder
52-
2. /src folder
53-
3. /dev folder
54-
55-
#### Root
56-
57-
In the root folder, you will see various files that relate to the configuration of the plugin. We set up our environment in a similar manner in Payload core and across other projects, so hopefully these will look familiar:
58-
59-
* **README**.md* - This contains instructions on how to use the template. When you are ready, update this to contain instructions on how to use your Plugin.
60-
* **package**.json* - Contains necessary scripts and dependencies. Overwrite the metadata in this file to describe your Plugin.
61-
* .**editorconfig** - Defines settings to maintain consistent coding styles.
62-
* .**eslintrc**.js - Eslint configuration for reporting on problematic patterns.
63-
* .**gitignore** - List specific untracked files to omit from Git.
64-
* .**prettierrc**.js - Configuration for Prettier code formatting.
65-
* **LICENSE** - As part of the open-source community, we ship all plugins with an MIT license but it is not required.
66-
* **tsconfig**.json - Configures the compiler options for TypeScript
67-
68-
**IMPORTANT***: You will need to modify these files.
69-
70-
#### Dev
71-
72-
In the dev folder, you’ll find a basic payload project, created with `npx create-payload-app` and the blank template.
73-
74-
The `samplePlugin` has already been installed to the `payload.config()` file in this project.
31+
Wrap your Auth.js configuration with the `withPayload` function before creating the NextAuth instance:
7532

7633
```ts
77-
plugins: [
78-
samplePlugin({
79-
enabled: false,
80-
})
81-
]
34+
// auth.ts
35+
import payloadConfig from "@payload-config";
36+
import NextAuth from "next-auth";
37+
import { withPayload } from "payload-authjs";
38+
import { authConfig } from "./auth.config";
39+
40+
export const { handlers, signIn, signOut, auth } = NextAuth(
41+
withPayload(authConfig, {
42+
payloadConfig,
43+
}),
44+
);
8245
```
8346

84-
Later when you rename the plugin or add additional options, make sure to update them here.
47+
And that's it! Now you can sign-in via Auth.js and you are automatically authenticated in Payload. Nice 🎉
8548

86-
You may wish to add collections or expand the test project depending on the purpose of your plugin. Just make sure to keep this dev environment as simplified as possible - users should be able to install your plugin without additional configuration required.
49+
### Advanced Usage
8750

88-
When you’re ready to start development, navigate into this folder with `cd dev`
89-
90-
And then start the project with `yarn dev` and pull up [http://localhost:3000/](http://localhost:3000/) in your browser.
91-
92-
#### Src
93-
94-
Now that we have our environment setup and we have a dev project ready to - it’s time to build the plugin!
95-
96-
**index.ts**
97-
98-
First up, the `src/index.ts` file. It is best practice not to build the plugin directly in this file, instead we use this to export the plugin and types from separate files.
99-
100-
**Plugin.ts**
101-
102-
To reiterate, the essence of a payload plugin is simply to extend the payload config - and that is exactly what we are doing in this file.
51+
If you want to customize the users collection, you can create a collection with the slug `users` and add the fields you need.
10352

10453
```ts
105-
export const samplePlugin =
106-
(pluginOptions: PluginTypes) =>
107-
(incomingConfig: Config): Config => {
108-
let config = { ...incomingConfig }
109-
110-
// do something cool with the config here
111-
112-
return config
113-
}
114-
54+
// users.ts
55+
import type { CollectionConfig } from "payload";
56+
57+
const Users: CollectionConfig = {
58+
slug: "users",
59+
fields: [
60+
{
61+
name: "roles",
62+
type: "json",
63+
},
64+
],
65+
};
66+
67+
export default Users;
11568
```
11669

117-
First, we receive the existing payload config along with any plugin options.
118-
119-
Then we set the variable `config` to be equal to the existing config.
120-
121-
From here, you can extend the config as you wish.
122-
123-
Finally, you return the config and that is it!
124-
125-
##### Spread Syntax
126-
127-
Spread syntax (or the spread operator) is a feature in JavaScript that uses the dot notation **(...)** to spread elements from arrays, strings, or objects into various contexts.
128-
129-
We are going to use spread syntax to allow us to add data to existing arrays without losing the existing data. It is crucial to spread the existing data correctly – else this can cause adverse behavior and conflicts with Payload config and other plugins.
130-
131-
Let’s say you want to build a plugin that adds a new collection:
70+
⚠ 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 `updateUserOnSignIn` option in the `withPayload` function:
13271

13372
```ts
134-
config.collections = [
135-
...(config.collections || []),
136-
// Add additional collections here
137-
]
138-
```
139-
140-
First we spread the `config.collections` to ensure that we don’t lose the existing collections, then you can add any additional collections just as you would in a regular payload config.
141-
142-
This same logic is applied to other properties like admin, hooks, globals:
143-
144-
```ts
145-
config.globals = [
146-
...(config.globals || []),
147-
// Add additional globals here
148-
]
149-
150-
config.hooks = {
151-
...(incomingConfig.hooks || {}),
152-
// Add additional hooks here
153-
}
154-
```
155-
156-
Some properties will be slightly different to extend, for instance the onInit property:
157-
158-
```ts
159-
import { onInitExtension } from './onInitExtension' // example file
160-
161-
config.onInit = async payload => {
162-
if (incomingConfig.onInit) await incomingConfig.onInit(payload)
163-
// Add additional onInit code by defining an onInitExtension function
164-
onInitExtension(pluginOptions, payload)
165-
}
166-
```
167-
168-
If you wish to add to the onInit, you must include the async/await. We don’t use spread syntax in this case, instead you must await the existing onInit before running additional functionality.
169-
170-
In the template, we have stubbed out a basic `onInitExtension` file that you can use, if not needed feel free to delete it.
171-
172-
##### File Aliasing
173-
174-
If your plugin uses packages or dependencies that are not browser compatible (fs, stripe, nodemailer, etc), you will need to alias them using your bundler to prevent getting errors in build.
175-
176-
You can read more about aliasing files with Webpack or Vite in the [excluding server modules](https://payloadcms.com/docs/admin/excluding-server-code#aliasing-server-only-modules) docs.
177-
178-
##### Types.ts
179-
180-
If your plugin has options, you should define and provide types for these options in a separate file which gets exported from the main index.ts.
181-
182-
```ts
183-
export interface PluginTypes {
184-
/**
185-
* Enable or disable plugin
186-
* @default false
187-
*/
188-
enabled?: boolean
189-
}
190-
```
191-
192-
If possible, include JSDoc comments to describe the options and their types. This allows a developer to see details about the options in their editor.
193-
194-
##### Testing
195-
196-
Having a test suite for your plugin is essential to ensure quality and stability. Jest is a popular testing framework, widely used for testing JavaScript and particularly for applications built with React.
197-
198-
Jest organizes tests into test suites and cases. We recommend creating individual tests based on the expected behavior of your plugin from start to finish.
199-
200-
Writing tests with Jest is very straightforward and you can learn more about how it works in the [Jest documentation.](https://jestjs.io/)
201-
202-
For this template, we stubbed out `plugin.spec.ts` in the `dev` folder where you can write your tests.
203-
204-
```ts
205-
describe('Plugin tests', () => {
206-
// Create tests to ensure expected behavior from the plugin
207-
it('some condition that must be met', () => {
208-
// Write your test logic here
209-
expect(...)
210-
})
211-
})
212-
```
213-
214-
## Best practices
215-
216-
With this tutorial and the `payload-plugin-template`, you should have everything you need to start building your own plugin.
217-
In addition to the setup, here are other best practices aim we follow:
218-
219-
* **Providing an enable / disable option:** For a better user experience, provide a way to disable the plugin without uninstalling it. This is especially important if your plugin adds additional webpack aliases, this will allow you to still let the webpack run to prevent errors.
220-
* **Include tests in your GitHub CI workflow**: If you’ve configured tests for your package, integrate them into your workflow to run the tests each time you commit to the plugin repository. Learn more about [how to configure tests into your GitHub CI workflow.](https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs)
221-
* **Publish your finished plugin to NPM**: The best way to share and allow others to use your plugin once it is complete is to publish an NPM package. This process is straightforward and well documented, find out more [creating and publishing a NPM package here.](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/).
222-
* **Add payload-plugin topic tag**: Apply the tag **payload-plugin **to your GitHub repository. This will boost the visibility of your plugin and ensure it gets listed with [existing payload plugins](https://github.com/topics/payload-plugin).
223-
* **Use [Semantic Versioning](https://semver.org/) (SemVar)** - With the SemVar system you release version numbers that reflect the nature of changes (major, minor, patch). Ensure all major versions reference their Payload compatibility.
224-
225-
# Questions
226-
Please contact [Payload](mailto:dev@payloadcms.com) with any questions about using this plugin template.
73+
// auth.ts
74+
export const { handlers, signIn, signOut, auth } = NextAuth(
75+
withPayload(authConfig, {
76+
payloadConfig,
77+
updateUserOnSignIn: true, // <-- Update the user on every sign-in
78+
}),
79+
);

dev/.env.example

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,19 @@
1-
DATABASE_URI=mongodb://127.0.0.1/plugin-development
2-
PAYLOAD_SECRET=hellohereisasecretforyou
1+
NEXT_PUBLIC_SERVER_URL=http://localhost:5000
2+
3+
# Payload CMS
4+
PAYLOAD_SECRET=secret
5+
DATABASE_URI=postgres://root:root@127.0.0.1:5432/payload-authjs
6+
7+
# Auth.js
8+
AUTH_SECRET=secret
9+
AUTH_TRUST_HOST=true
10+
11+
AUTH_GITHUB_ID=
12+
AUTH_GITHUB_SECRET=
13+
14+
AUTH_KEYCLOAK_ISSUER=http://localhost:8080/realms/myrealm
15+
AUTH_KEYCLOAK_ID=client-id
16+
AUTH_KEYCLOAK_SECRET=
17+
18+
EMAIL_SERVER=
19+
EMAIL_FROM=
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { auth } from "@/auth";
2+
import { getPayloadUser } from "../../../../../src";
3+
import { SignInButton } from "./SignInButton";
4+
import { SignOutButton } from "./SignOutButton";
5+
6+
const AuthOverview = async () => {
7+
const session = await auth();
8+
const payloadUser = await getPayloadUser();
9+
10+
return (
11+
<div>
12+
<p>{session?.user ? <SignOutButton /> : <SignInButton />}</p>
13+
<br />
14+
<h3>Auth.js</h3>
15+
<div style={{ background: "gray", padding: "5px", borderRadius: "10px" }}>
16+
{JSON.stringify(session?.user, null, 2)}
17+
</div>
18+
<br />
19+
<h3>Payload CMS</h3>
20+
<div style={{ background: "gray", padding: "5px", borderRadius: "10px" }}>
21+
{JSON.stringify(payloadUser, null, 2)}
22+
</div>
23+
</div>
24+
);
25+
};
26+
27+
export default AuthOverview;

dev/src/app/(app)/_components/ExampleList.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
import config from "@payload-config";
22
import { getPayloadHMR } from "@payloadcms/next/utilities";
3+
import { getPayloadUser } from "../../../../../src";
34

45
const payload = await getPayloadHMR({ config });
56

67
const ExampleList = async () => {
8+
const payloadUser = await getPayloadUser();
9+
if (!payloadUser) {
10+
return <p>Sign in to see examples</p>;
11+
}
12+
713
let examples;
814
try {
915
examples = await payload.find({
1016
collection: "examples",
17+
// Use the current user's access level
18+
overrideAccess: false,
19+
user: payloadUser,
1120
});
1221
} catch (error: any) {
1322
return <p>Failed to load examples: {error.message}</p>;
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { signIn } from "@/auth";
2+
3+
export function SignInButton() {
4+
return (
5+
<form
6+
action={async () => {
7+
"use server";
8+
await signIn();
9+
}}
10+
>
11+
<button type="submit">Sign In</button>
12+
</form>
13+
);
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { signOut } from "@/auth";
2+
3+
export function SignOutButton() {
4+
return (
5+
<form
6+
action={async () => {
7+
"use server";
8+
await signOut();
9+
}}
10+
>
11+
<button type="submit">Sign Out</button>
12+
</form>
13+
);
14+
}

dev/src/app/(app)/page.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
import AuthOverview from "./_components/AuthOverview";
12
import ExampleList from "./_components/ExampleList";
23

34
const Page = async () => {
45
return (
56
<article className="container">
7+
<AuthOverview />
8+
<br />
69
<ExampleList />
710
</article>
811
);
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { handlers } from "@/auth";
2+
3+
export const { GET, POST } = handlers;

0 commit comments

Comments
 (0)