Setting Environment Variables for Preview Environments in Porter
Last updated: February 9, 2026
When working with preview environments in Porter, you may need to set specific environment variables that differ from your main application. This article explains two methods to achieve this.
Method 1: Using porter.yaml
You can set environment variables for preview environments in your porter.yaml file:
version: v2
services:
- name: api
type: web
port: 3000
env:
NODE_ENV: production
previews:
env:
NODE_ENV: development
DATABASE_URL: your_preview_database_url
You can also set environment variables for preview environments using the Porter CLI:
Use Case: Setting Dynamic Preview App URLs
For cases where you need to set environment variables based on the deployed preview environment (such as NEXT_PUBLIC_APP_URL), you'll need to deploy twice when the PR is first created:
Initial deployment: Deploy your preview environment normally
Get the assigned domain: After the preview environment is fully deployed, run:
porter app run -x <pr-branch> <app-name> -- env | grep PORTER_DOMAINSThis returns a comma-separated list of domains assigned to your app.
Set the environment variable: Use the domain from the previous step:
porter env set -x <pr-branch-name> -a <app-name> -v NEXT_PUBLIC_APP_URL=<domain-from-previous-step>This will redeploy your app with the new environment variable.
Note: This two-step process is only required for the initial PR deployment. Subsequent deployments for the same PR will work normally with a single deployment.
porter env set -x <preview-env-name> -a <app-name> --variables DATABASE_URL=<value>Replace <pr-branch-name> with the name of your PR branch (any special characters must be replaced by -), <app-name> with your application name, and <domain-from-previous-step> with the backend URL.
Important Notes
Environment variables set for preview environments will be available during both the build process and runtime.
Any values not specifically overridden for preview environments will be inherited from the base app configuration.
Porter automatically makes all environment variables defined for an application available during the build process.
By using these methods, you can ensure that your preview environments use the correct database URL or any other environment-specific configurations.