Hooks in Payload CMS enable you to inject custom logic at various points in the lifecycle of API calls. A common use case is ensuring that a user is logged in before performing certain actions.
Creating the Hook
const checkUserLoggedIn = ({ req, operation }) => {
if (!req.user) {
throw new Error('You must be logged in to perform this action.');
}
};
const myCollection = {
slug: 'secure-data',
hooks: {
beforeChange: [checkUserLoggedIn],
},
};
export default myCollection;
How It Works
- The
req.userobject is populated only when a user is authenticated. - If no user is found, the hook throws an error, preventing unauthorized changes.
- You can attach this hook to any collection or operation (create, update, delete).