Environment Variables

Environment Variables are a way to store sensitive information that your application needs to function. This could be anything from API keys to Database credentials. Payload allows you to easily use Environment Variables within your config and throughout your application.

Next.js Applications

If you are using Next.js, no additional setup is required other than creating your .env file.

To use Environment Variables, add a .env file to the root of your project:

1
project-name/
2
├─ .env
3
├─ package.json
4
├─ payload.config.ts

Here is an example of what an .env file might look like:

1
SERVER_URL=localhost:3000
2
DATABASE_URI=mongodb://localhost:27017/my-database

To use Environment Variables in your Payload Config, you can access them directly from process.env:

1
import { buildConfig } from 'payload'
2
3
export default buildConfig({
4
serverURL: process.env.SERVER_URL,
5
// ...
6
})

Client-side Environments

For security and safety reasons, the Admin Panel does not include Environment Variables in its client-side bundle by default. But, Next.js provides a mechanism to expose Environment Variables to the client-side bundle when needed.

If you are building a Custom Component and need to access Environment Variables from the client-side, you can do so by prefixing them with NEXT_PUBLIC_.

For example, if you've got the following Environment Variable:

1
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_XXXXXXXXXXXXXXXXXX

This key will automatically be made available to the client-side Payload bundle and can be referenced in your Custom Component as follows:

1
'use client'
2
import React from 'react'
3
4
const stripeKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
5
6
const MyClientComponent = () => {
7
// do something with the key
8
9
return (
10
<div>
11
My Client Component
12
</div>
13
)
14
}

For more information, check out the Next.js Documentation.

Outside of Next.js

If you are using Payload outside of Next.js, we suggest using the dotenv package to handle Environment Variables from .env files. This will automatically load your Environment Variables into process.env.

To do this, import the package as high up in your application as possible:

1
import dotenv from 'dotenv'
2
dotenv.config()
3
4
import { buildConfig } from 'payload'
5
6
export default buildConfig({
7
serverURL: process.env.SERVER_URL,
8
// ...
9
})
Next

Database