Node, React and MongoDB Headless CMS and Application Framework
npx @tessl/cli install tessl/npm-payload@1.1.0Payload is a headless content management system and application framework that provides a complete backend solution for web applications. It combines a powerful admin interface built with React, flexible content modeling capabilities, and comprehensive APIs (REST, GraphQL, and Local Node APIs) to enable developers to build scalable web applications and websites.
npm install payloadimport payload from "payload";
import { Payload } from "payload";For CommonJS:
const payload = require("payload");
const { Payload } = require("payload");import payload from "payload";
// Initialize Payload
await payload.initAsync({
secret: process.env.PAYLOAD_SECRET,
mongoURL: process.env.DATABASE_URI,
express: app, // Your Express app
});
// Create a document
const newPost = await payload.create({
collection: "posts",
data: {
title: "My First Post",
content: "Hello, world!",
status: "published",
},
});
// Find documents
const posts = await payload.find({
collection: "posts",
where: {
status: {
equals: "published",
},
},
});
// Update a document
const updatedPost = await payload.update({
collection: "posts",
id: postId,
data: {
title: "Updated Title",
},
});Payload is built around several key components:
Primary CRUD operations for interacting with collections and managing content. Essential for all content management workflows.
// Create operations
function create<T>(options: CreateOptions<T>): Promise<T>;
// Read operations
function find<T>(options: FindOptions): Promise<PaginatedDocs<T>>;
function findByID<T>(options: FindByIDOptions): Promise<T>;
// Update operations
function update<T>(options: UpdateOptions<T>): Promise<T>;
// Delete operations
function delete<T>(options: DeleteOptions): Promise<T>;
interface CreateOptions<T> {
collection: string;
data: Partial<T>;
depth?: number;
locale?: string;
fallbackLocale?: string;
user?: User;
overrideAccess?: boolean;
showHiddenFields?: boolean;
}
interface FindOptions {
collection: string;
where?: Where;
sort?: string;
limit?: number;
page?: number;
depth?: number;
locale?: string;
fallbackLocale?: string;
user?: User;
overrideAccess?: boolean;
showHiddenFields?: boolean;
}Operations for managing global documents (singleton content like site settings, navigation, etc.).
function findGlobal<T>(options: FindGlobalOptions): Promise<T>;
function updateGlobal<T>(options: UpdateGlobalOptions): Promise<T>;
interface FindGlobalOptions {
slug: string;
depth?: number;
locale?: string;
fallbackLocale?: string;
user?: User;
overrideAccess?: boolean;
showHiddenFields?: boolean;
}
interface UpdateGlobalOptions {
slug: string;
data: any;
depth?: number;
locale?: string;
fallbackLocale?: string;
user?: User;
overrideAccess?: boolean;
showHiddenFields?: boolean;
}Complete user authentication and management system with login, password reset, email verification, and account locking.
function login<T>(options: LoginOptions): Promise<LoginResult & { user: T }>;
function forgotPassword(options: ForgotPasswordOptions): Promise<ForgotPasswordResult>;
function resetPassword(options: ResetPasswordOptions): Promise<ResetPasswordResult>;
function unlock(options: UnlockOptions): Promise<boolean>;
function verifyEmail(options: VerifyEmailOptions): Promise<boolean>;
interface LoginResult {
token?: string;
user: User;
exp?: number;
}
interface LoginOptions {
collection: string;
data: {
email: string;
password: string;
};
req?: PayloadRequest;
res?: Response;
depth?: number;
locale?: string;
fallbackLocale?: string;
overrideAccess?: boolean;
showHiddenFields?: boolean;
}Document versioning system for tracking changes and restoring previous versions of content.
function findVersions<T>(options: FindVersionsOptions): Promise<PaginatedDocs<T>>;
function findVersionByID<T>(options: FindVersionByIDOptions): Promise<T>;
function restoreVersion<T>(options: RestoreVersionOptions): Promise<T>;
function findGlobalVersions<T>(options: FindGlobalVersionsOptions): Promise<PaginatedDocs<T>>;
function findGlobalVersionByID<T>(options: FindGlobalVersionByIDOptions): Promise<T>;
function restoreGlobalVersion<T>(options: RestoreGlobalVersionOptions): Promise<T>;Comprehensive configuration system for defining collections, globals, fields, authentication, and admin settings.
interface Config {
serverURL?: string;
collections?: CollectionConfig[];
globals?: GlobalConfig[];
admin?: AdminConfig;
auth?: AuthConfig;
email?: EmailConfig;
upload?: UploadConfig;
localization?: LocalizationConfig;
typescript?: TypeScriptConfig;
graphQL?: GraphQLConfig;
cors?: CORSConfig;
csrf?: CSRFConfig;
express?: ExpressConfig;
routes?: {
admin?: string;
api?: string;
graphQL?: string;
graphQLPlayground?: string;
};
rateLimit?: RateLimitConfig;
hooks?: {
afterError?: AfterErrorHook;
};
telemetry?: boolean;
debug?: boolean;
loggerOptions?: LoggerOptions;
}Rich set of field types for modeling content including text fields, relationships, file uploads, rich text editing, and complex nested structures.
// Core field types
interface TextField extends BaseField {
type: 'text';
maxLength?: number;
minLength?: number;
hasMany?: boolean;
}
interface RichTextField extends BaseField {
type: 'richText';
editor?: RichTextEditorConfig;
}
interface RelationshipField extends BaseField {
type: 'relationship';
relationTo: string | string[];
hasMany?: boolean;
maxDepth?: number;
}
interface UploadField extends BaseField {
type: 'upload';
relationTo: string;
}
interface ArrayField extends BaseField {
type: 'array';
fields: Field[];
minRows?: number;
maxRows?: number;
}System for storing and managing user-specific settings, UI state, and document preferences.
function findPreference<T>(options: PreferenceRequest): Promise<T | null>;
function updatePreference<T>(options: PreferenceUpdateRequest): Promise<Preference>;
function deletePreference(options: PreferenceRequest): Promise<Preference | null>;
interface PreferenceRequest {
key: string;
user: User;
req: PayloadRequest;
overrideAccess?: boolean;
}
interface PreferenceUpdateRequest extends PreferenceRequest {
value: T;
}// Main Payload class
class Payload {
config: SanitizedConfig;
collections: { [slug: string]: Collection };
globals: Globals;
logger: pino.Logger;
express: Express;
router: Router;
// Initialization
init(options: InitOptions): void;
initAsync(options: InitOptions): Promise<void>;
// Utility methods
getAdminURL(): string;
getAPIURL(): string;
// Crypto utilities
encrypt: (text: string) => string;
decrypt: (encryptedText: string) => string;
}
// Initialization options
interface InitOptions {
secret: string;
mongoURL?: string | false;
express?: Express;
email?: EmailOptions;
local?: boolean;
onInit?: () => void | Promise<void>;
}
// Result types
interface PaginatedDocs<T> {
docs: T[];
totalDocs: number;
limit: number;
totalPages: number;
page: number;
pagingCounter: number;
hasPrevPage: boolean;
hasNextPage: boolean;
prevPage?: number;
nextPage?: number;
}
// Base document types
interface TypeWithID {
id: string | number;
createdAt?: string;
updatedAt?: string;
}
interface TypeWithVersion<T> extends TypeWithID {
version: T;
createdAt: string;
updatedAt: string;
}
// Query types
interface Where {
[key: string]: any;
and?: Where[];
or?: Where[];
}
// User and auth types
interface User extends TypeWithID {
email?: string;
resetPasswordToken?: string;
resetPasswordExpiration?: string;
salt?: string;
hash?: string;
loginAttempts?: number;
lockUntil?: number;
}
// Base error types
class APIError extends Error {
status: number;
data?: any;
constructor(message?: string, status?: number, data?: any);
}
class ValidationError extends APIError {
constructor(message?: string, data?: any);
}
class Forbidden extends APIError {
constructor(message?: string);
}
class NotFound extends APIError {
constructor(message?: string);
}
// Authentication errors
class AuthenticationError extends APIError {
constructor(message?: string);
}
class LockedAuth extends APIError {
constructor(message?: string);
}
// Configuration errors
class InvalidConfiguration extends APIError {
constructor(message?: string);
}
class DuplicateCollection extends APIError {
constructor(message?: string, slug?: string);
}
class DuplicateGlobal extends APIError {
constructor(message?: string, slug?: string);
}
// Field errors
class InvalidFieldName extends APIError {
constructor(message?: string, fieldName?: string);
}
class InvalidFieldRelationship extends APIError {
constructor(message?: string);
}
class MissingFieldType extends APIError {
constructor(message?: string);
}
class MissingFieldInputOptions extends APIError {
constructor(message?: string);
}
// Collection errors
class MissingCollectionLabel extends APIError {
constructor(message?: string, slug?: string);
}
class TimestampsRequired extends APIError {
constructor(message?: string);
}
// File upload errors
class FileUploadError extends APIError {
constructor(message?: string);
}
class ErrorDeletingFile extends APIError {
constructor(message?: string);
}
class MissingFile extends APIError {
constructor(message?: string);
}