robj's avatar
Level 9

VITE_ building with local .env file for Vapor

Hey all, this foxed me for a while when Prod wouldn't pick up the correct settings and when I figured it out I was "doh!"

When I deploy to vapor it builds locally and uses my dev .env file for VITE_ variables - not a problem if these are the same as Prod but where they're not I'm having to swap in the Prod settings then remembering to swap them out again after deployment - risky.

Is there a neat way around this?

Thanks, RobJ.

0 likes
2 replies
LaryAI's avatar
Level 58

Hello RobJ,

When deploying with Vapor, you indeed want to ensure that your production environment variables are used during the build process, especially for your VITE_ prefixed variables. Here's a solution that you can use to avoid manually swapping your .env files.

You can create a separate .env file for your production environment, for example, .env.production. In this file, you would place all your production environment variables, including those prefixed with VITE_.

Then, before you deploy with Vapor, you can use a script to copy the production environment variables into your .env file or directly specify the environment file to use during the build process. Here's an example of how you can modify your vapor.yml to use the production environment variables:

deployments:
  production:
    build:
      - 'cp .env.production .env'
      - 'npm run build'

Alternatively, if you're using Vite, you can specify the mode in which to run the build command, which will then use the corresponding .env.[mode] file. For example:

deployments:
  production:
    build:
      - 'npm run build -- --mode production'

Make sure you have a .env.production file with the correct variables. Vite will automatically load the .env.production file when building for production mode.

Remember to include your .env.production file in your version control system if it does not contain sensitive information. If it does, you should use Vapor's environment variable management to set those variables securely.

This way, you can keep your development environment variables separate from your production ones and avoid the risk of accidentally deploying with the wrong configuration.

I hope this helps you streamline your deployment process with Vapor and Vite!

robj's avatar
Level 9

@LaryAI Hmm, I get this is a solution, but feels more like a workaround - I would have to have the .env.production on my system so need to do a vapor env:pull production during the build process and the delete it afterwards.

Also, and obvious when you think about it, all the VITE_ values need to be in the unencrypted .env too.

Please or to participate in this conversation.