nextload

Next.js and Payload boilerplate with Better Auth, blog, cart, runtime theming and hybrid caching

nextload preview

Overview

Summary generated from the README

NextLoad is a full-stack boilerplate that embeds Payload CMS 3 in Next.js 16 with MongoDB. It includes Better Auth login synced to Payload users, a blog engine, e-commerce collections with a client-side cart, and a user dashboard. Styling uses Tailwind CSS 4 and shadcn/ui. It requires MongoDB; Redis, SMTP, Google OAuth and Cloudinary are optional.

Features

  • Better Auth email/password and Google OAuth synced with the Payload Users collection
  • Blog with posts, categories, tags, reading time, sitemap and robots generation
  • Product, coupon and review collections with a cart drawer and checkout route handler
  • Runtime OKLCH theme palettes set from Site Settings in the admin panel
  • Hybrid Redis or in-memory cache with purge hooks on banner changes
  • Cookie consent global, announcement banners, newsletter collection and Nodemailer emails

Good for

  • Launching a Next.js site that combines a blog, a small shop and authenticated user accounts
  • Starting a full-stack project that needs admin-editable branding and theming
  • Building a content-driven app with user dashboards on MongoDB

From the author

NEXT LOAD by Scalvio — production-ready Next.js + Payload CMS boilerplate

Get started

This repository is a GitHub template: create your own copy of it in one click.

Create a repository from this template

README

NextLoad Banner

Next.js React TypeScript Payload CMS MongoDB Redis Better Auth Tailwind CSS shadcn/ui

NextLoad

NextLoad is a production-grade full-stack boilerplate built on Next.js 16, Payload CMS 3.0, and MongoDB. It provides authentication, an embedded headless content management system, dynamic runtime theming, hybrid caching, anti-tampering security controls, a full blog engine, e-commerce cart capabilities, and a responsive component library.


Table of Contents

  1. Overview
  2. Tech Stack
  3. Architecture and Project Structure
  4. Core Features
  5. API Reference
  6. Environment Variables
  7. Getting Started
  8. Available Scripts
  9. Deployment
  10. License

Overview

NextLoad solves the initial setup overhead of starting a modern web application. Instead of spending weeks gluing together database drivers, authentication cookies, an admin dashboard, cache stores, and UI primitives, NextLoad delivers an integrated system where:

  • Content editors manage pages, blog posts, site settings, themes, banners, and cookies from the embedded Payload CMS studio.
  • Users authenticate via email/password or Google OAuth using Better Auth sessions.
  • Developers build with React 19 Server Components and client hooks backed by TypeScript strict mode.
  • Caching runs automatically on Redis when available, or seamlessly in-memory with automatic cleanup when Redis is omitted.

Tech Stack

LayerTechnologyVersionPurpose
FrameworkNext.js16.3.3App Router, Server Actions, Route Handlers
UI LibraryReact / React DOM19.2.6Component rendering and concurrency
LanguageTypeScript5.7.3Strict type checking and project aliases
CMS PlatformPayload CMS3.90.2Headless CMS directly embedded into Next.js
DatabaseMongoDB>=6.0Primary document database via Mongoose adapter
Cache StoreRedis / In-Memoryioredis 6.0Hybrid cache with automatic memory fallback
AuthenticationBetter Auth1.7.5Session management, OAuth 2.0, password flows
Auth UIBetter Auth UI1.7.26Pre-built authentication interface components
Auth BridgePayload Better Auth0.13.0Syncs Better Auth users with Payload collection
CSS FrameworkTailwind CSS4.3.3CSS-first architecture with OKLCH dynamic tokens
Component PrimitivesRadix UI / Base UILatestAccessible modal, drawer, dropdown, and toast primitives
Component Stylingshadcn/ui4.21.0Custom accessible React components
IconsLucide React1.47.0Application and interface icon system
Media StorageCloudinary / Local6.19.3Media uploads with automatic sharp image processing
Email ServiceNodemailer10.0.10SMTP transactional email transport

Architecture and Project Structure

NextLoad uses Next.js route groups to maintain strict separation between public frontend pages and administrative CMS routes.

nextload/
├── app/
│   ├── (frontend)/                    # Public-facing application routes
│   │   ├── auth/                      # Authentication views (login, signup, reset)
│   │   ├── blog/                      # Blog engine (posts, categories, tags)
│   │   │   ├── [slug]/                # Single post reader
│   │   │   ├── category/[slug]/       # Category archive
│   │   │   └── tag/[slug]/            # Tag archive
│   │   ├── dashboard/                 # Protected user dashboard
│   │   ├── layout.tsx                 # Root frontend layout with providers
│   │   └── page.tsx                   # Landing page showcasing all platform features
│   ├── (payload)/                     # Embedded Payload CMS route group
│   │   ├── admin/                     # Payload CMS studio UI (/admin)
│   │   ├── api/                       # Payload native REST & GraphQL handlers
│   │   ├── custom.scss                # Admin studio theme overrides
│   │   └── layout.tsx                 # Payload admin layout wrapper
│   ├── api/                           # Application API route handlers
│   │   ├── banners/active/            # Active banner query with TTL cache
│   │   ├── checkout/                  # Cart checkout and order placement
│   │   ├── cookie-consent/            # Cookie policy settings
│   │   ├── newsletter/                # Newsletter subscription handler
│   │   ├── site-settings/             # Global site branding and security settings
│   │   └── upload/                    # File and avatar upload endpoint
│   ├── globals.css                    # Tailwind CSS v4 design tokens and theme rules
│   ├── robots.ts                      # Dynamic robots.txt generation
│   └── sitemap.ts                     # Dynamic XML sitemap generator
│
├── components/
│   ├── basic/                         # Production application feature components
│   │   ├── blog/                      # Blog post cards, hero, breadcrumbs, sidebar
│   │   ├── cart/                      # Cart drawer, items, state store, price utils
│   │   ├── context/                   # Global SiteSettingsContext and cache provider
│   │   ├── dashboard/                 # User dashboard shell, profile, order history
│   │   ├── footer/                    # Site footer, payment badges, newsletter box
│   │   ├── header/                    # Main navigation, mega-menu, mobile drawer
│   │   ├── security/                  # Zero-CPU DevTools and anti-tamper listener
│   │   └── theme/                     # OKLCH runtime CSS variable injector
│   └── ui/                            # shadcn/ui reusable design primitives
│
├── config/
│   ├── header.ts                      # Navigation links and header layout config
│   └── site.ts                        # Application meta information and fallback defaults
│
├── payload/
│   ├── access/                        # Role-based access control helpers
│   ├── auth/                          # Better Auth server configuration and client
│   ├── collections/                   # Payload content schema definitions
│   │   ├── blog/                      # Posts, Categories, Tags collections
│   │   ├── ecommerch/                 # Products, Categories, Coupons, Reviews
│   │   ├── Banners.ts                 # Notification and announcement banners
│   │   ├── Media.ts                   # Uploaded media with sharp optimization
│   │   ├── Newsletter.ts              # Email newsletter subscribers
│   │   └── Users.ts                   # Application users with role fields
│   ├── globals/                       # Payload global singleton schemas
│   │   ├── CookieConsent.ts           # Cookie banner texts and category toggles
│   │   └── SiteSettings.ts            # Global branding, OKLCH colors, security toggles
│   ├── lib/
│   │   └── cache/index.ts             # Universal hybrid Redis/Memory cache engine
│   └── payload.config.ts              # Payload CMS master configuration
│
├── .env.example                       # Documented environment variable template
├── components.json                    # shadcn/ui CLI configuration
├── next.config.ts                     # Next.js configuration and image domains
├── package.json                       # Dependencies, engines, and build scripts
└── tsconfig.json                      # Strict TypeScript compiler options

Core Features

Authentication and User Management

Authentication is powered by Better Auth and synchronized with the Payload Users collection:

  • Email and Password registration, login, and session validation.
  • Google OAuth 2.0 social login support.
  • Secure HTTP-only cookies with configurable 30-day session expiry.
  • Role-based authorization distinguishing between standard users and administrators.
  • Password reset, forgot password, and email verification email workflows.
  • User profile updates, avatar uploads via Cloudinary, and password change flows.
  • Header user menu, slide-over mobile drawer, and dedicated /auth routing.

Payload CMS 3.0 Integration

Payload CMS is embedded directly inside the Next.js runtime:

  • Admin Studio accessible at /admin without running an independent backend process.
  • Lexical rich-text editor with headings, lists, links, image embedding, and code formatting.
  • Collections:
    • Users: Accounts, authentication links, and system roles.
    • Posts: Blog articles with slugs, excerpt, rich text, reading time, and author relationships.
    • Categories and Tags: Taxonomy for grouping blog and product content.
    • Media: Image management with sharp resizing and optional Cloudinary storage.
    • Banners: Scheduled announcement bars with top, bottom, or floating positioning.
    • Newsletter: Subscriber collection for marketing updates.
    • Products, Coupons, Reviews: E-commerce catalog schemas.
  • Globals:
    • SiteSettings: Live brand names, descriptions, contact info, social links, theme colors, and security.
    • CookieConsent: Cookie banner text, privacy links, and category preferences.
  • Built-in GraphQL API and interactive GraphQL Playground at /api/graphql-playground.

Dynamic OKLCH Theming System

NextLoad provides an interactive runtime theming engine:

  • Theme colors are defined in Payload Admin under Site Settings > Theme Colors.
  • Administrators choose primary and secondary hex colors through an interactive color picker.
  • The server generates matching 50 to 950 OKLCH color palettes in real time.
  • The ThemeInjector component writes these tokens directly into CSS root variables.
  • Works in tandem with next-themes for system, light, and dark mode toggling without flash of unstyled content (FOUC).

Universal Hybrid Caching Engine

High-traffic endpoints utilize a hybrid caching layer (payload/lib/cache/index.ts):

  • Redis Mode: If REDIS_URL is set in your .env file, the cache engine connects via ioredis with automatic retry strategies.
  • In-Memory Fallback: If REDIS_URL is omitted or temporarily unreachable, the engine falls back to an in-memory Map with custom TTL expiration. Expired entries are cleaned up every 5 minutes.
  • Automatic Purging: When administrators update or delete banners in Payload Admin, collection lifecycle hooks (afterChange, afterDelete) immediately purge the active cache key (banners:active).
  • Client Cache: The SiteSettingsContext caches site settings in localStorage for 5 hours, deduplicates concurrent network requests, and updates in the background using stale-while-revalidate.

Anti-Tampering and DevTools Security

Configurable security controls protect frontend assets and sensitive operations:

  • Configured directly inside Payload Admin (Site Settings > Security & DevTools Protection).
  • Inspect Lock: Blocks F12, Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+Shift+C, Cmd+Option+I, and Cmd+Option+J.
  • Source View Lock: Intercepts Ctrl+U and Cmd+Option+U.
  • Save Lock: Prevents saving page sources via Ctrl+S or Cmd+S.
  • Context Menu Protection: Disables the right-click inspect menu while preserving native right-click inside editable form fields (input, textarea).
  • Text Selection Protection: Optionally prevents text selection across marketing and protected pages.
  • Admin Exemption: Logged-in administrators bypass all restrictions automatically.
  • Performance: Zero-CPU implementation using passive browser event listeners.

Blog Engine and SEO

A complete publishing system ready out of the box:

  • Clean URLs: /blog, /blog/[slug], /blog/category/[slug], /blog/tag/[slug].
  • Reading time estimation calculated from word count.
  • Breadcrumb navigation with structured breadcrumb components.
  • Social sharing triggers for Twitter, Facebook, LinkedIn, and clipboard copy.
  • Automated sitemap.xml generated dynamically at app/sitemap.ts covering static routes and published posts.
  • Automated robots.txt generated at app/robots.ts.

E-Commerce and Cart System

A lightweight shopping cart built with client-side state:

  • Slide-over Cart Drawer (components/basic/cart/CartDrawer.tsx).
  • Reactive cart items, quantity adjustments, item removals, and real-time subtotal calculation.
  • Free shipping progress bar indicating distance to shipping threshold.
  • Formatted currency rendering using standard number formatters.
  • Checkout route handler (/api/checkout) ready for payment gateway integration (Stripe, SSLCommerz, PayPal).

User Dashboard

A dedicated workspace for authenticated users at /dashboard:

  • Profile tab: Update personal information, email, and upload profile pictures.
  • Orders tab: Review purchase history, transaction dates, item lists, and delivery statuses.
  • Notifications tab: Manage email notification preferences and marketing alerts.
  • Security tab: Password change form and active session details.

Transactional Email Service

Email delivery handled by Nodemailer with HTML templates:

  • Password reset email with secure verification link.
  • Email verification message for new user signups.
  • Password change confirmation alert.
  • Development fallback: logs email content directly to the terminal when SMTP variables are not configured.

API Reference

EndpointMethodCache StrategyDescription
/api/site-settingsGET5 hours browser/CDN + localStorageReturns branding, navigation, theme colors, and security settings.
/api/banners/activeGET5 min hybrid cache (auto-purged on update)Returns active announcement banners for display.
/api/cookie-consentGET1 hour hybrid cacheReturns cookie consent modal text and privacy category configuration.
/api/checkoutPOSTNo cacheProcesses cart checkout and generates order record.
/api/newsletterPOSTNo cacheSubscribes an email address to the newsletter collection.
/api/uploadPOSTNo cacheAccepts multipart file uploads and pipes to Cloudinary or local storage.
/api/auth/*ALLNo cacheBetter Auth endpoints (sign-in, sign-up, sign-out, session, oauth).
/api/graphqlPOSTQuery-dependentPayload CMS GraphQL API endpoint.
/api/graphql-playgroundGETBrowser cacheInteractive browser interface for running GraphQL queries.
/api/[collection]ALLPayload defaultStandard Payload REST API for collections (e.g. /api/posts, /api/media).

Environment Variables

Copy .env.example to .env and fill in the values for your environment:

cp .env.example .env
VariableRequiredDefaultDescription
DATABASE_URLYesmongodb://127.0.0.1:27017/nextloadMongoDB connection URI.
PAYLOAD_SECRETYes—Secret string used to sign Payload tokens (minimum 32 characters).
BETTER_AUTH_SECRETYes—Secret string used for Better Auth session signing (minimum 32 characters).
BETTER_AUTH_URLYeshttp://localhost:3000Public base URL of your application.
NEXT_PUBLIC_APP_URLYeshttp://localhost:3000Application URL exposed to client-side components.
REDIS_URLNo—Redis connection URL (e.g. redis://default:password@host:6379). If omitted, in-memory cache is used.
SMTP_HOSTNosmtp.hostinger.comSMTP outgoing mail server hostname.
SMTP_PORTNo465SMTP port (465 for SSL, 587 for TLS).
SMTP_SECURENotrueSet to true for port 465, or false for port 587.
SMTP_USERNo—SMTP username or email address.
SMTP_PASSNo—SMTP account password or app password.
SMTP_FROMNo"NextLoad <[email protected]>"Default sender header for outgoing emails.
GOOGLE_CLIENT_IDNo—Google Cloud OAuth 2.0 client ID for social login.
GOOGLE_CLIENT_SECRETNo—Google Cloud OAuth 2.0 client secret.
NEXT_PUBLIC_CLOUDINARY_CLOUD_NAMENo—Cloudinary cloud name for media uploads.
NEXT_PUBLIC_CLOUDINARY_API_KEYNo—Cloudinary API key.
CLOUDINARY_API_SECRETNo—Cloudinary API secret.

Getting Started

1. Prerequisites

  • Node.js: Version 18.20.2 or >=20.9.0
  • Package Manager: pnpm version 9, 10, or 11
  • Database: MongoDB instance running locally or via MongoDB Atlas
  • Cache (Optional): Redis instance (e.g. Upstash, Redis Cloud, or local Docker)

2. Installation

Clone the repository and install dependencies:

git clone https://github.com/shatadhru/NextLoad.git
cd nextload
pnpm install

3. Generate Payload Import Map and Types

Initialize Payload CMS dependencies:

npx payload generate:importmap
pnpm generate:types

4. Configure Environment

Copy .env.example to .env and set your secrets:

cp .env.example .env

To generate a secure 32-character secret on Windows (PowerShell) or Linux/macOS:

# Linux / macOS / Git Bash
openssl rand -base64 32

# Windows PowerShell
-join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEach-Object {[char]$_})

5. Start Development Server

Run the development server:

pnpm dev

Open the following URLs in your browser:

On your first visit to /admin, Payload will prompt you to create the initial administrative account.


Available Scripts

ScriptCommandPurpose
pnpm devnext devStarts the Next.js development server with hot module reloading.
pnpm devsafeNext cache clean + next devDeletes the local .next cache directory before starting development.
pnpm buildnext buildCompiles and optimizes the full-stack application for production.
pnpm startnext startRuns the compiled production server.
pnpm linteslint .Runs ESLint across all TypeScript and React files.
pnpm payloadpayloadRuns Payload CMS CLI commands.
pnpm generate:typespayload generate:typesGenerates TypeScript interfaces from Payload collection schemas.
pnpm generate:importmappayload generate:importmapRebuilds the Payload component import map for the admin panel.
pnpm init:projectnode payload/scripts/init.mjsRuns initial project setup helper scripts.

Deployment

Node.js / Docker Server

NextLoad runs as a standard Node.js server:

  1. Set all production environment variables in your hosting environment.
  2. Build the production application:
    pnpm build
    
  3. Start the server:
    pnpm start
    

Vercel / Cloud Platforms

  • Connect your GitHub repository to Vercel.
  • Configure the root directory to nextload if deploying from a subfolder.
  • Add all required environment variables (DATABASE_URL, PAYLOAD_SECRET, BETTER_AUTH_SECRET, BETTER_AUTH_URL, NEXT_PUBLIC_APP_URL).
  • Use the standard build command: pnpm build.

License

This project is open-source and licensed under the MIT License.

More Starters & boilerplates templates

acme-website screenshot

acme-website

Payload 3 starter with Better Auth, Postgres, S3 storage, a blog and composable layout and motion components

122
v3
Next.js
Updated 2 weeks ago
payload-starter screenshot

payload-starter

Next.js 16 and Payload 3 starter with PostgreSQL, role-based admin access, shadcn/ui and SEO helpers

100
v3
Next.js
Updated 4 months ago
patload-theme-quantum-leap screenshot

patload-theme-quantum-leap

Dark admin UI theme for Payload with a custom dashboard home and login view

76
v3
Next.js
Updated 1 years ago