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
Payload provides a convenient way to run standalone scripts, which can be useful for tasks like seeding your database or performing one-off operations.
In standalone scripts, you can simply import the Payload Config and use it right away. If you need an initialized copy of Payload, you can then use the getPayload
function. This can be useful for tasks like seeding your database or performing other one-off operations.
You can then execute the script using payload run
. Example: if you placed this standalone script in src/seed.ts
, you would execute it like this:
The payload run
command does two things for you:
- It loads the environment variables the same way Next.js loads them, eliminating the need for additional dependencies like
dotenv
. The usage ofdotenv
is not recommended, as Next.js loads environment variables differently. By usingpayload run
, you ensure consistent environment variable handling across your Payload and Next.js setup. - It initializes tsx, allowing direct execution of TypeScript files manually installing tools like tsx or ts-node.
Troubleshooting
If you encounter import-related errors, you have 2 options:
Option 1: enable swc mode by appending --use-swc
to the payload
command:
Example:
Note: Install @swc-node/register in your project first. While swc mode is faster than the default tsx mode, it might break for some imports.
Option 2: use an alternative runtime like bun
While we do not guarantee support for alternative runtimes, you are free to use them and disable payloads own transpilation by appending the --disable-transpilation
flag to the payload
command:
You will need to have bun installed on your system for this to work.