Using Payload outside Next.js

Payload can be used completely outside of Next.js which is helpful in cases like running scripts, using Payload in a separate backend service, or using Payload's Local API to fetch your data directly from your database in other frontend frameworks like Sveltekit, Remix, Nuxt, and similar.

Importing the Payload Config outside of Next.js

Your Payload Config likely has imports which need to be handled properly, such as CSS imports and similar. If you were to try and import your config without any Node support for SCSS / CSS files, you'll see errors that arise accordingly.

This is especially relevant if you are importing your Payload Config outside of a bundler context, such as in standalone Node scripts.

For these cases, you can use Payload's importConfig function to handle importing your config safely. It will handle everything you need to be able to load and use your Payload Config, without any client-side files present.

Here's an example of a seed script that creates a few documents for local development / testing purposes, using Payload's importConfig function to safely import Payload, and the getPayload function to retrieve an initialized copy of Payload.

1
// We are importing `getPayload` because we don't need HMR
2
// for a standalone script. For usage of Payload inside Next.js,
3
// you should always use `import { getPayloadHMR } from '@payloadcms/next/utilities'` instead.
4
import { getPayload } from 'payload'
5
6
// This is a helper function that will make sure we can safely load the Payload Config
7
// and all of its client-side files, such as CSS, SCSS, etc.
8
import { importConfig } from 'payload/node'
9
10
import path from 'path'
11
import { fileURLToPath } from 'node:url'
12
import dotenv from 'dotenv'
13
14
// In ESM, you can create the "dirname" variable
15
// like this. We'll use this with `dotenv` to load our `.env` file, if necessary.
16
const filename = fileURLToPath(import.meta.url)
17
const dirname = path.dirname(filename)
18
19
// If you don't need to load your .env file,
20
// then you can skip this part!
21
dotenv.config({
22
path: path.resolve(dirname, '../.env'),
23
})
24
25
const seed = async () => {
26
// Get a local copy of Payload by passing your config
27
const payload = await getPayload({ config })
28
29
const user = await payload.create({
30
collection: 'users',
31
data: {
32
email: 'dev@payloadcms.com',
33
password: 'some-password'
34
}
35
})
36
37
const page = await payload.create({
38
collection: 'pages',
39
data: {
40
title: 'My Homepage',
41
// other data to seed here
42
}
43
})
44
}
45
46
// Call the function here to run your seed script
47
seed()
Next

REST API