Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: builds custom server example #2920

Merged
merged 5 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions examples/custom-server/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
MONGODB_URI=mongodb://localhost/payload-example-custom-server
PAYLOAD_SECRET=PAYLOAD_CUSTOM_SERVER_EXAMPLE_SECRET_KEY
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000
NEXT_PUBLIC_SERVER_URL=http://localhost:3000
PAYLOAD_SEED=true
PAYLOAD_DROP_DATABASE=true
5 changes: 5 additions & 0 deletions examples/custom-server/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
root: true,
extends: ['@payloadcms'],
ignorePatterns: ['**/payload-types.ts'],
}
7 changes: 7 additions & 0 deletions examples/custom-server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
build
dist
node_modules
package-lock.json
.env
.next
.vercel
1 change: 1 addition & 0 deletions examples/custom-server/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/payload-types.ts
8 changes: 8 additions & 0 deletions examples/custom-server/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
printWidth: 100,
parser: "typescript",
semi: false,
singleQuote: true,
trailingComma: "all",
arrowParens: "avoid",
};
118 changes: 118 additions & 0 deletions examples/custom-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Payload Custom Server Example

This example demonstrates how to serve your front-end alongside [Payload](https://github.com/payloadcms/payload) in a single Express server. This pattern will cut down on hosting costs and can simplify your deployment process.

## Quick Start

To spin up this example locally, follow these steps:

1. First clone the repo
1. Then `cd YOUR_PROJECT_REPO && cp .env.example .env`
1. Next `yarn && yarn dev`
1. Now `open http://localhost:3000/admin` to access the admin panel
1. Login with email `dev@payloadcms.com` and password `test`

That's it! Changes made in `./src` will be reflected in your app. See the [Development](#development) section for more details.

## How it works

When you use Payload, you plug it into _**your**_ Express server. That's a fundamental difference between Payload and other application frameworks. It means that when you use Payload, you're technically _adding_ Payload to _your_ app, and not building a "Payload app".

One of the strengths of this pattern is that it lets you do powerful things like integrate your Payload instance directly with your front-end. This will allow you to host Payload alongside a fully dynamic, CMS-integrated website or app on a single, combined server—while still getting all of the benefits of a headless CMS.

### Express

In every Payload app is a `server.ts` file in which you instantiate your own Express server and attach Payload to it. This is where you can can add any custom Express middleware or routes you need to serve your front-end. To combine Payload with your framework on the same server, we need to do three main things:

1. Modify your `server.ts` file to build and serve your front-end using the APIs provided by your framework
2. Modify your `package.json` scripts include your framework's build commands
3. Use a separate `tsconfig.server.json` file to build the server, because your front-end may require incompatible TypeScript settings

This example demonstrates how to do this with [Next.js](https://nextjs.org), although the same principles apply to any front-end framework like [Vue](https://vuejs.org), [Nuxt](https://nuxt.com), or [SvelteKit](https://kit.svelte.dev). If your framework does not yet have instructions listed here, please consider contributing them to this example for others to use. To quickly eject Next.js from this example, see the [Eject](#eject) section.

#### Next.js

For Next.js apps, your `server.ts` file looks something like this:

```ts
import next from 'next'
import nextBuild from 'next/dist/build'

// Instantiate Express and Payload
// ...

// If building, start the server to build the Next.js app then exit
if (process.env.NEXT_BUILD) {
app.listen(3000, async () => {
await nextBuild(path.join(__dirname, '../'))
process.exit()
})

return
}

// Attach Next.js routes and start the server
const nextApp = next({
dev: process.env.NODE_ENV !== 'production',
})

const nextHandler = nextApp.getRequestHandler()

app.get('*', (req, res) => nextHandler(req, res))

nextApp.prepare().then(() => {
app.listen(3000)
})
```

Check out the [server.ts](./src/server.ts) in this repository for a complete working example. You can also see the [Next.js docs](https://nextjs.org/docs/advanced-features/custom-server) for more details.

Then your `package.json` might look something like this:

```json
// ...
"scripts": {
// ...
"build:payload": "payload build",
"build:server": "tsc --project tsconfig.server.json",
"build:next": "next build",
"build": "yarn build:payload && yarn build:server && yarn build:next",
}
```

Check out the [package.json](./src/package.json) in this repository for a complete working example. You can also see the [Next.js docs](https://nextjs.org/docs/api-reference/cli#build) for more details.

## Eject

To eject Next.js from this template and replace it with another front-end framework, follow these steps:

1. Remove the `next`, `react`, and `react-dom` dependencies from your `package.json` file
1. Remove the `next.config.js` and `next-env.d.ts` files from your project root
1. Remove the `./src/app` directory and all of its contents

Now you can install and setup any other framework you'd like. Follow the [Express](#express) instructions above to make the necessary changes to build and serve your front-end.

## Development

To spin up this example locally, follow the [Quick Start](#quick-start).

### Seed

On boot, a seed script is included to scaffold a basic database for you to use as an example. This is done by setting the `PAYLOAD_DROP_DATABASE` and `PAYLOAD_SEED` environment variables which are included in the `.env.example` by default. You can remove these from your `.env` to prevent this behavior. You can also freshly seed your project at any time by running `yarn seed`. This seed creates an admin user with email `dev@payloadcms.com`, password `test`, and a `home` page.

> NOTICE: seeding the database is destructive because it drops your current database to populate a fresh one from the seed template. Only run this command if you are starting a new project or can afford to lose your current data.

## Production

To run Payload in production, you need to build and serve the Admin panel. To do so, follow these steps:

1. First, invoke the `payload build` script by running `yarn build` or `npm run build` in your project root. This creates a `./build` directory with a production-ready admin bundle.
1. Then, run `yarn serve` or `npm run serve` to run Node in production and serve Payload from the `./build` directory.

### Deployment

The easiest way to deploy your project is to use [Payload Cloud](https://payloadcms.com/new/import), a one-click hosting solution to deploy production-ready instances of your Payload apps directly from your GitHub repo. You can also choose to self-host your app, check out the [Deployment](https://payloadcms.com/docs/production/deployment) docs for more details.

## Questions

If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions).
5 changes: 5 additions & 0 deletions examples/custom-server/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
13 changes: 13 additions & 0 deletions examples/custom-server/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
require('dotenv').config()

module.exports = {
publicRuntimeConfig: {
SERVER_URL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
},
images: {
domains: [
'localhost',
// Your domain(s) here
],
},
jacobsfletch marked this conversation as resolved.
Show resolved Hide resolved
}
4 changes: 4 additions & 0 deletions examples/custom-server/nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"ext": "ts,tsx",
"exec": "ts-node src/server.ts"
}
52 changes: 52 additions & 0 deletions examples/custom-server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "payload-example-custom-server",
"description": "Payload custom server example.",
"version": "1.0.0",
"main": "dist/server.js",
"license": "MIT",
"scripts": {
"dev": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts nodemon",
"seed": "rm -rf media && cross-env PAYLOAD_SEED=true PAYLOAD_DROP_DATABASE=true PAYLOAD_CONFIG_PATH=src/payload.config.ts ts-node src/server.ts",
"build:payload": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload build",
"build:server": "tsc --project tsconfig.server.json",
"build:next": "cross-env PAYLOAD_CONFIG_PATH=dist/payload.config.js NEXT_BUILD=true node dist/server.js",
"build": "cross-env NODE_ENV=production yarn build:payload && yarn build:server && yarn copyfiles && yarn build:next",
"serve": "cross-env PAYLOAD_CONFIG_PATH=dist/payload.config.js NODE_ENV=production node dist/server.js",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png}\" dist/",
"generate:types": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types",
"generate:graphQLSchema": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:graphQLSchema",
"lint": "eslint src",
"lint:fix": "eslint --fix --ext .ts,.tsx src"
},
"dependencies": {
"dotenv": "^8.2.0",
"escape-html": "^1.0.3",
"express": "^4.17.1",
"next": "^13.4.7",
"payload": "^1.8.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@payloadcms/eslint-config": "^0.0.1",
"@types/escape-html": "^1.0.2",
"@types/express": "^4.17.9",
"@types/node": "18.11.3",
"@types/react": "18.0.21",
"@typescript-eslint/eslint-plugin": "^5.51.0",
"@typescript-eslint/parser": "^5.51.0",
"copyfiles": "^2.4.1",
"cross-env": "^7.0.3",
"eslint": "^8.19.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-filenames": "^1.3.2",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-simple-import-sort": "^10.0.0",
"nodemon": "^2.0.22",
"prettier": "^2.7.1",
"ts-node": "^9.1.1",
"typescript": "^4.8.4"
}
}
Binary file added examples/custom-server/public/favicon.ico
Binary file not shown.
15 changes: 15 additions & 0 deletions examples/custom-server/public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.gutterLeft {
padding-left: var(--gutter-h);
}

.gutterRight {
padding-right: var(--gutter-h);
}
33 changes: 33 additions & 0 deletions examples/custom-server/src/app/_components/Gutter/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React, { forwardRef, Ref } from 'react'

import classes from './index.module.scss'

type Props = {
left?: boolean
right?: boolean
className?: string
children: React.ReactNode
ref?: Ref<HTMLDivElement>
}

export const Gutter: React.FC<Props> = forwardRef<HTMLDivElement, Props>((props, ref) => {
const { left = true, right = true, className, children } = props

return (
<div
ref={ref}
className={[
left && classes.gutterLeft,
right && classes.gutterRight,
className,
classes.gutter,
]
.filter(Boolean)
.join(' ')}
>
{children}
</div>
)
})

Gutter.displayName = 'Gutter'
Loading