• This repository has been archived on 12/Apr/2024
  • Stars
    star
    306
  • Rank 131,683 (Top 3 %)
  • Language
    TypeScript
  • Created about 1 year ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A utility to deploy Payload serverlessly within a Next.js app

Next + Payload Serverless

This package contains a set of utilities to allow Payload to be deployed seamlessly, serverless, within an existing NextJS project. It adds the Payload admin UI into the NextJS /app folder and adds all Payload endpoints into the pages/api folder.

To do so, this package exposes a few different helpers. To get started, follow the steps below:

1. Add this package and Payload to your project

npm install @payloadcms/next-payload payload
# or
yarn add @payloadcms/next-payload payload

2. Run the command to extend your Next app with Payload

npx next-payload install
# or
yarn next-payload install

3. Your .env should include:

# mongo connection string
MONGODB_URI=mongodb://127.0.0.1/create-next-app-serverless
# payload secret
PAYLOAD_SECRET=SOME_SECRET
# path to your payload.config file
PAYLOAD_CONFIG_PATH=payload/payload.config.ts

4. Add withPayload to your next.config

Payload needs to inject some requirements into your Next config in order to function properly. To install withPayload, you need to import it into your next.config.js file. Here's an example:

// next.config.js
const path = require("path");
const { withPayload } = require("@payloadcms/next-payload");

module.exports = withPayload(
  {
    // your Next config here
  },
  {
    // The second argument to `withPayload`
    // allows you to specify paths to your Payload dependencies
    // and configure the admin route to your Payload CMS.

    // Point to your Payload config (Required)
    configPath: path.resolve(__dirname, "./payload/payload.config.ts"),

    // Point to custom Payload CSS (optional)
    cssPath: path.resolve(__dirname, "./css/my-custom-payload-styles.css"),

    // Point to your exported, initialized Payload instance (optional, default shown below`)
    payloadPath: path.resolve(process.cwd(), "./payload/payloadClient.ts"),

    // Set a custom Payload admin route (optional, default is `/admin`)
    // NOTE: Read the "Set a custom admin route" section in the payload/next-payload README.
    adminRoute: "/admin",
  }
);

And then you're done. Have fun!

Using the local API

The payload/payloadClient.ts file will be added for you after running yarn next-payload install (step 2). You can import getPayloadClient from that file from within server components to leverage the Payloads Local API. The Local API does not use REST or GraphQL, and runs directly on your server talking directly to your database, which saves massively on HTTP-induced latency.

Here is an example:

// app/[slug]/page.tsx

import React from "react";
import { notFound } from "next/navigation";
import { getPayloadClient } from "../../payload/payloadClient";

const Page = async ({ params: { slug } }) => {
  const payload = await getPayloadClient();

  const pages = await payload.find({
    collection: "pages",
    where: {
      slug: {
        equals: slug || "home",
      },
    },
  });

  const page = pages.docs[0];

  if (!page) return notFound();

  return <h1>Hello, this is the "{page.slug}" page!</h1>;
};

export async function generateStaticParams() {
  const payload = await getPayloadClient();

  const pages = await payload.find({
    collection: "pages",
    limit: 0,
  });

  return pages.docs.map(({ slug }) => ({ slug }));
}

export default Page;

Set a custom admin route

Payload makes it simple to set a custom admin route. However, since we are using next-payload and relying on Next.js to handle all routing, we need to also tell Next.js to rewrite all admin related routes to Payload.

This is handled automatically by wrapping the Next.js configuration in withPayload, which by default sets the admin route to /admin. If you wish to change this default behavior, we need to do a couple of things.

In the following example, we are changing the admin route to /dashboard.

1. Configure the admin route in payload/payload.config.ts as per the Payload documentation.

export default buildConfig({
  // ... Payload config goes here
  routes: {
    admin: "/dashboard",
  },
});

2. Rename the admin directory under /app to dashboard.

3. Set adminRoute: "/dashboard", in the Payload configuration in next.config.js as per the documentation above.

Known gotchas

Cold start delays

With the nature of serverless functions, you are bound to encounter "cold start" delays when your serverless functions spin up for the first time. Once they're "warm", the problem will go away for a few minutes until the functions become dormant again. But there's little that this package can do about that issue, unfortunately.

If you'd like to avoid cold starts with your Payload API, you can deploy on a server-based platform like Payload Cloud instead.

Need to sign up for additional vendors

To deploy Payload on Vercel, you'll need to configure additional vendors for the following:

  • Database (MongoDB Atlas)
  • File storage (AWS S3 or similar) with Payload's Cloud Storage Plugin
  • Email service (Resend, Sendgrid)

If you don't want to go out and sign up for a separate file hosting service, you can just use Payload Cloud, which gives you file storage, a MongoDB Atlas database, email service by Resend, and lots more.

Developing this plugin

Using yarn link to develop this plugin locally is currently the best way to implement new features or debug existing behavior. Here are the steps to get setup:

Setting up the plugin for dev:

  1. Clone this repo
  2. cd into the folder you cloned this repo into and run yarn
  3. Then run yarn link
  4. Uncomment this line

Setting up a linked project:

  1. Clone the next-payload-demo repo
  2. Follow the getting started section in the next-payload-demo README
  3. cd into the folder you cloned the demo into and run yarn link @payloadcms/next-payload
  4. Run yarn dev and you should see the demo running on localhost:3000

Making changes to the plugin:

  1. Make your changes to the plugin and save
  2. Run yarn build in the plugin folder (you NEED to do this to see your changes)
  3. Refresh your browser and see the changes you made!

If you run into any issues while developing, please open an issue in this repo so we can get it resolved. Thanks for contributing!

More Repositories

1

payload

The best way to build a modern backend + admin UI. No black magic, all TypeScript, and fully open-source, Payload is both an app framework and a headless CMS.
TypeScript
17,486
star
2

website

The official Next.js website for payloadcms.com
TypeScript
298
star
3

payload-3.0-demo

The official demo for Payload 3.0
TypeScript
227
star
4

nextjs-custom-server

A TypeScript boilerplate for combining Payload and Next.js into a single Express server
TypeScript
177
star
5

plugin-cloud-storage

The official cloud storage plugin for Payload
TypeScript
127
star
6

website-cms

The CMS behind payloadcms.com
TypeScript
123
star
7

public-demo

The official public demo for Payload
TypeScript
111
star
8

plugin-seo

The official SEO plugin for Payload
TypeScript
88
star
9

remix-server

Monorepo template with Remix and Payload
TypeScript
84
star
10

next-payload-demo

The official demo for next-payload
TypeScript
81
star
11

template-ecommerce

TypeScript
69
star
12

custom-website-series

A fully custom website built with Payload and Next.js
TypeScript
65
star
13

plugin-form-builder

The official form builder plugin for Payload
TypeScript
65
star
14

template-ecommerce-nextjs

TypeScript
52
star
15

plugin-stripe

The official Stripe plugin for Payload
TypeScript
45
star
16

plugin-search

The official search plugin for Payload
TypeScript
44
star
17

plugin-nested-docs

The official nested docs plugin for Payload
TypeScript
30
star
18

payload-admin-bar

An admin bar for React apps using Payload
TypeScript
21
star
19

migrate-mongo-example

Payload project using migrate-mongo to demonstrate migrations
JavaScript
20
star
20

plugin-password-protection

The official password protection plugin for Payload
TypeScript
18
star
21

custom-field-guide

TypeScript
18
star
22

plugin-zapier

The official Zapier plugin for Payload
TypeScript
17
star
23

access-control-demo

A demo of the powerful access control measures built into Payload
TypeScript
16
star
24

template-website

TypeScript
16
star
25

plugin-redirects

The official redirects plugin for Payload
TypeScript
15
star
26

vercel-deploy-payload-postgres

One-click deployment template of Payload 3.0 on Vercel
TypeScript
15
star
27

plugin-sentry

The official Sentry plugin for Payload
TypeScript
15
star
28

plugin-template

A template for creating your own Payload plugin
JavaScript
14
star
29

template-website-nextjs

13
star
30

enterprise-website-cms

An enterprise website CMS that can show how to build large websites on a design system, at scale
TypeScript
12
star
31

create-payload-app

CLI for creating a new Payload project
12
star
32

next-auth-frontend

TypeScript
11
star
33

game-admin-guide

An entire admin system for an imaginary game
TypeScript
10
star
34

plugin-relationship-object-ids

A Payload plugin to store all relationship IDs as ObjectIDs
JavaScript
8
star
35

next-auth-cms

TypeScript
7
star
36

plugin-cloud

The official Payload Cloud plugin
TypeScript
6
star
37

enterprise-website

An enterprise website frontend that can show how to build large websites on a design system, at scale
TypeScript
6
star
38

speed-test

A speed test for use in comparisons.
TypeScript
5
star
39

drizzle-test

TypeScript
5
star
40

discord-bot

A bot to help manage Payload's Discord
TypeScript
5
star
41

db-mongoose

The official Mongoose / MongoDB database adapter for Payload
JavaScript
5
star
42

wp-to-payload

A head-to-head comparison about what it's like to build in WP and ACF vs. Payload.
PHP
4
star
43

form-builder-example-website

Boilerplate Next.js website for the official Payload CMS Form Builder plugin
TypeScript
4
star
44

rich-text-with-markdown

TypeScript
4
star
45

eslint-config

The official Payload ESLint config
JavaScript
4
star
46

blog-rbac

JavaScript
2
star
47

blank

1
star
48

template-blank

TypeScript
1
star
49

typescript-jest-vscode

A tutorial for how to set up Payload with TypeScript, Jest, and VSCode Debugging
TypeScript
1
star