Skip to content

[astro] Server environment variables in preview mode  #853

@dertieran

Description

@dertieran

I'm testing out the astro integration from solid-start@0.3.0-alpha.3 in an existing 0.2.26 project.

I had some server only environment variables in a .env file.

DATABASE_URL=<some database url>

I changed the usage from process.env to import.meta.env according to the astro docs.
(Using process.env also still worked when running astro dev)

- const DATABASE_URL = process.env.DATABASE_URL;
+ const DATABASE_URL = import.meta.env.DATABASE_URL;
if (!DATABASE_URL) throw new Error('No database url defined')

But when I then ran astro build and then astro preview the environment variables where not defined.

I already debugged this a bit and noticed

Astro either converts or inlines the import.meta.env without a prefix.
https://github.com/withastro/astro/blob/b24607069ed1b305b47ca25171e682f7c71603eb/packages/astro/src/vite-plugin-env/index.ts#L30-L39

Because the .env is loaded in the build step the code above is basically converted back to

const DATABASE_URL = process.env.DATABASE_URL;

But the .env file is not loaded when running astro preview so process.env.DATABASE_URL is not defined.

Not sure if this should be the responsibility of solid-start or could also be handled by @astrojs/node.

I fixed it for me right now by importing this env.js file

import dotenv from "dotenv";
dotenv.config();

In handler.js

import "./env.js";
import startHandler from "~/entry-server";

So I could test the build locally, but not sure if this is a good solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions