Payload CMS provides robust access control features that allow you to define permissions at a granular level. With custom access controls, you can limit access to collections, fields, and individual documents based on user roles or other conditions. This guide will walk through setting up access control in Payload CMS, from basic role permissions to more complex, conditional logic.
Introduction
Access control in Payload CMS is set at the collection level, where you can configure both read and write permissions. These permissions are defined by functions that determine whether a user can perform specific actions, allowing fine-grained control over who can access or modify data.
Access Control for Collections
To restrict access to a collection, you can define access rules within the collection’s configuration file. These rules use Payload’s access functions, which evaluate conditions and return true (allow) or false (deny).
import { CollectionConfig } from 'payload/types';
const Posts: CollectionConfig = {
slug: 'posts',
access: {
read: ({ req: { user } }) => {
return user && user.role === 'Admin'; // Only allow users with 'Admin' role to read
},
create: ({ req: { user } }) => {
return user && user.role === 'Admin'; // Only admins can create posts
},
update: ({ req: { user } }) => {
return user && user.role === 'Admin'; // Only admins can update posts
},
delete: ({ req: { user } }) => {
return user && user.role === 'Admin'; // Only admins can delete posts
},
},
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'content', type: 'richText' },
],
};
export default Posts;
Field-Level Access Control
Field-level access control allows you to restrict access to specific fields within a collection, even if a user has access to the collection itself.
{
name: 'salary',
type: 'number',
access: {
read: ({ req: { user } }) => user && user.role === 'Admin', // Only admins can read this field
},
}
Conclusion
Access control in Payload CMS is a powerful way to enforce security and data integrity in your application. By configuring collection, field, and document-level access rules, you can ensure that each user has the appropriate level of access to your content. Whether it’s setting up basic role-based permissions or defining advanced conditional logic, Payload CMS provides the flexibility to handle a wide variety of access control needs for secure and scalable applications.