6.7 KiB
Payload Auth Example
This Payload Auth Example demonstrates how to implement Payload Authentication into all types of applications. Follow the Quick Start to get up and running quickly.
IMPORTANT—This example includes a fully integrated Next.js App Router front-end that runs on the same server as Payload. If you are working on an application running on an entirely separate server, there are various fully working, separately running front-ends made explicitly for this example, including:
Those applications run directly alongside this one. Follow the instructions in each respective README to get started. If you are setting up authentication for another front-end, please consider contributing to this repo with your own example!
To learn more about this, check out how Payload can be used in its various headless capacities.
Quick Start
To spin up this example locally, follow these steps:
-
Clone this repo
-
cdinto this directory and runpnpm i --ignore-workspace*,yarn, ornpm install*If you are running using pnpm within the Payload Monorepo, the
--ignore-workspaceflag is needed so that pnpm generates a lockfile in this example's directory despite the fact that one exists in root. -
cp .env.example .envto copy the example environment variablesAdjust
PAYLOAD_PUBLIC_SITE_URLin the.envif your front-end is running on a separate domain or port. -
pnpm dev,yarn devornpm run devto start the server- Press
ywhen prompted to seed the database
- Press
-
open http://localhost:3000to access the home page -
open http://localhost:3000/adminto access the admin panel- Login with email
demo@payloadcms.comand passworddemo
- Login with email
That's it! Changes made in ./src will be reflected in your app. See the Development section for more details.
How it works
Collections
See the Collections docs for details on how to extend this functionality.
-
Users (Authentication)
Users are auth-enabled and encompass both admins and regular users based on the value of their
rolesfield. Onlyadminusers can access your admin panel to manage your content whereasusercan authenticate on your front-end and access-controlled interfaces. See Access Control for more details.Local API
On the server, Payload provides all operations needed to authenticate users server-side using the Local API. In Next.js that might look something like this:
import { headers as getHeaders } from 'next/headers.js' import { getPayloadHMR } from '@payloadcms/next' import config from '../../payload.config' export default async function AccountPage({ searchParams }) { const headers = getHeaders() const payload = await getPayloadHMR({ config: configPromise }) const { permissions, user } = await payload.auth({ headers }) if (!user) { redirect( `/login?error=${encodeURIComponent('You must be logged in to access your account.')}&redirect=/account`, ) } return ... }HTTP
The
userscollection also opens an http-layer to expose all auth-related operations through the REST and GraphQL APIs, including:MeLoginLogoutRefresh TokenVerify EmailUnlockForgot PasswordReset Password
This might look something like this:
await fetch('/api/users/me', { method: 'GET', credentials: 'include', headers: { 'Content-Type': 'application/json', }, })NOTE: You can still use the HTTP APIs on the server if you don't have access to the Local API.
Security
The cors, csrf, and cookies settings are all configured to ensure that the admin panel and front-end can communicate with each other securely.
For additional help, see the Authentication docs.
Access Control
Basic role-based access control is setup to determine what users can and cannot do based on their roles, which are:
admin: They can access the Payload admin panel to manage your application. They can see all data and make all operations.user: They cannot access the Payload admin panel and have a limited access to operations based on their user.
A beforeChange field hook called protectRoles is placed on this to automatically populate roles with the user role when a new user is created. It also protects roles from being changed by non-admins.
Development
To spin up this example locally, follow the Quick Start.
Seed
On boot, a seed migration performed to create a user with email demo@payloadcms.com, password demo, the role admin.
NOTICE: seeding the database is destructive because it drops your current database to populate a fresh one from the seed template. Only run this command if you are starting a new project or can afford to lose your current data.
Production
To run Payload in production, you need to build and serve the Admin panel. To do so, follow these steps:
- First invoke the
payload buildscript by runningpnpm build,yarn build, ornpm run buildin your project root. This creates a./builddirectory with a production-ready admin bundle. - Then run
pnpm serve,yarn serve, ornpm run serveto run Node.js in production and serve Payload from the./builddirectory.
Deployment
If you are using an integrated Next.js setup, the easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js. Otherwise, easiest way to deploy your project is to use Payload Cloud, a one-click hosting solution to deploy production-ready instances of your Payload apps directly from your GitHub repo. You can also deploy your app manually, check out the deployment documentation for full details.
Questions
If you have any issues or questions, reach out to us on Discord or start a GitHub discussion.