GithubHelp home page GithubHelp logo

expatfile / next-runtime-env Goto Github PK

View Code? Open in Web Editor NEW
311.0 311.0 9.0 37.07 MB

Next.js Runtime Environment Configuration - Populates your environment at runtime rather than build time.

Home Page: https://www.npmjs.com/package/next-runtime-env

License: MIT License

JavaScript 6.06% TypeScript 91.45% Shell 2.49%

next-runtime-env's People

Contributors

1k00 avatar andrewmclagan avatar anthonycrowcroft avatar bb-in-hoodie avatar davevanhoorn avatar dependabot[bot] avatar expatfile-bot avatar headfox avatar hofmannz avatar miguel-adapttech avatar ryantimesten avatar sunrabbit123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

next-runtime-env's Issues

The automated release is failing 🚨

🚨 The automated release from the 1.x branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the 1.x branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The release 1.7.1 on branch 1.x cannot be published as it is out of range.

Based on the releases published on other branches, only versions within the range >=1.7.0 <1.7.0 can be published from branch 1.x.

The following commits are responsible for the invalid release:

  • ci: πŸ”– support building maintenance releases (db46ef1)
  • docs: ⬆️ upgrade examples (15c1a10)
  • docs: πŸ“š reference v2 in readme (088ba74)
  • ci: βœ… run tests on node version 18 and 20 (f8d14eb)
  • build: ⬆️ upgrade deps (5f09c2a)
  • ci: πŸ‘· upgrade actions/checkout to v4 (e824da3)
  • ci: πŸ‘· remove dependabot in favour of snyk (29a2e5b)

Those commits should be moved to a valid branch with git merge or git cherry-pick and removed from branch 1.x with git revert or git reset.

A valid branch could be main.

See the workflow configuration documentation for more details.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Doesn't work when a page.tsx throws an unhandled exception.

The library stops working when a page.tsx throws an unhandled error. This results in a cascade of issues in my app.

Expected behaviour: read env vars even tho there is an unhandled exception in a page/layout..

// app/page.tsx
import { env } from 'next-runtime-env';
const NETWORKING_ENVIRONMENT = env('NEXT_PUBLIC_NETWORKING_ENVIRONMENT')

async function getData(): Promise<number> {
    throw new Error('This is a test error');
    return 1;
}

export default async function Home() {
    const pageData = await getData();

    return (
       <div>
home page
<div>ENV: {NETWORKING_ENVIRONMENT}</div> This stops reading/working...
</div>
    );
}

Supporting output: 'standalone' Configuration

Excited to find this package supporting the Build Once, Run Anywhere philosophy.

In order to keep our docker container super tiny, we turned on standalone output within the next.config.js.

const nextConfig = {
  // Automatically leverage output traces to reduce image size
  // https://nextjs.org/docs/advanced-features/output-file-tracing
  output: 'standalone',
}

We run npm run build and the public/__ENV.js is generated. However, that's at build time. We then copy over the public folder into .next/standalone/public as well as .next/static into .next/standalone/.next/static.

From the docs:

This minimal server does not copy the public or .next/static folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the standalone/public and standalone/.next/static folders manually, after which server.js file will serve these automatically.

When we start up our built application, NEXT_PUBLIC_FOO=foo node .next/standalone/server.js, the plugin's code to write the public environment variables does not seem to run. The public/__ENV.js is not created and/or the plugin code never executes.

Have you experienced this before with the output: 'standalone'?

Any help would be appreciated! Thank you.

Also working for non-public Variables?

Hi
I understand, that it will fetch the "NEXT_Public" prefixed variables at runtime. But will it also do this for non-public-variables which are supposed to be used only on server side and just not meant to go to the client?

In the examples server only variables are only used in "getstaticprops", which is only executed for generating static stuff during build time.

How to access runtime env var in next.config.js

I have the following nextConfig:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "standalone",
  // If set, use the given URL prefix for fetching static content instead of serving
  // it directly from the next app.
  assetPrefix: process.env.NEXT_PUBLIC_CDN_PREFIX,
};

The focus here is assetPrefix. I want this value to be read at runtime to inform the client where to fetch static assets. The issue is, even though I have this env var set, it doesn't work because I believe the final value for assetPrefix is determined at build time, but the env var is only set during run time.

For the rest of my app I'm solving this by using next-runtime-env but I can't seem to get that to work in next.config.js.

Is there a way to set assetPrefix based on an env var at runtime? I see that env isn't available for version 3 of next-runtime-env so I'm not sure how I'd use it. I tried to use the development version because I see it adds env back but I can't get the installation to work. Do you know if using env will work, e.g.

const { env } = require("next-runtime-env");

const nextConfig = {
  output: "standalone",
  // If set, use the given URL prefix for fetching static content instead of serving
  // it directly from the next app.
  assetPrefix: env(NEXT_PUBLIC_CDN_PREFIX),
};

I'm running NextJS from a Docker image. I build the app as part of building the image, which I'd prefer to keep doing rather than building as part of the command when I run a container from that image.

I'm using NextJS version 14.0.2 and next-runtime-env 3.0.1.

Server Side environment variables not working

When following the instructions in the example app's README.md, the server side environment variables are undefined.

cd examples/with-app-router
yarn build
NEXT_PUBLIC_FOO=foo-value BAR=bar-value yarn start

and visiting http://localhost:3000/server-side I see

image

however visiting http://localhost:3000/client-side I see

image

I tried a few things, and the only way I could get the server side version to work was to set NODE_ENV=development when using yarn start.

after running NEXT_PUBLIC_FOO=foo-value BAR=bar-value NODE_ENV=development yarn start I see
image

This is not going to work in production because we need our NextJS app to run in production mode. It seems like the only way this library works as stated (identical server + client side environment variables) is if we run the app in development mode. Am I missing something?

Thanks heaps for this library by the way, gobsmacked when I learned of NextJS's approach to environment variables and this seems like a great way to solve it - I'm just unable to get server side env variables working in production mode though.

Option to disable logging when using makeEnvPublic

When using makeEnvPublic in next.config.js:

const { makeEnvPublic } = require('next-runtime-env')

makeEnvPublic([
  'API_BASE_URL',
])

It logs βœ“ Prefixed environment variable 'API_BASE_URL' (next-runtime-env) on every server start. Both in local development mode and on production environments this creates a lot of (duplicate) noise in the logs. An option to disable this would be a nice and simple addition:

makeEnvPublic([
  'API_BASE_URL',
], {
  loglevel: 'silent' // Other options could 'warn', 'info'
})

Should next-runtime-env work with Docker and docker-compose?

I've tested the package and it works wonderfully in the examples you provide πŸŽ‰.
However, I fail to make it work with Docker and Docker Compose πŸ₯€.

The idea would be to define the variables in a .env next to the docker.compose.yml, not next to the nextjs project. Then, pass the variables to the container at the startup.

I've prepared an example here.
I get undefined at the client side.
Note the __ENV.js file is present, but empty (window.__ENV = {}).

lib doesn't work for next 14.2

Hey everyone,
today I upgraded my app with new 14.2.1 next.js version and found next-runtime-env crashing my app in the development runtime:

TypeError: (0 , react_1.createContext) is not a function
    at Object.<anonymous> (/blabla/.next/server/chunks/node_modules_927e2a._.js:1942:48)
    at [project]/node_modules/next-runtime-env/build/provider/env-context.js [app-route] (ecmascript) (/blabla/.next/server/chunks/node_modules_927e2a._.js:1944:3)
    at instantiateModule (/blabla/.next/server/chunks/[turbopack]_runtime.js:520:23)
    at getOrInstantiateModuleFromParent (/blabla/.next/server/chunks/[turbopack]_runtime.js:572:12)
    at commonJsRequire (/blabla/.next/server/chunks/[turbopack]_runtime.js:136:20)
    at Object.<anonymous> (/blabla/.next/server/chunks/node_modules_927e2a._.js:1954:23)
    at [project]/node_modules/next-runtime-env/build/provider/env-provider.js [app-route] (ecmascript) (/blabla/.next/server/chunks/node_modules_927e2a._.js:1972:3)
    at instantiateModule (/blabla/.next/server/chunks/[turbopack]_runtime.js:520:23)
    at getOrInstantiateModuleFromParent (/blabla/.next/server/chunks/[turbopack]_runtime.js:572:12)
    at commonJsRequire (/blabla/.next/server/chunks/[turbopack]_runtime.js:136:20)
    at Object.<anonymous> (/blabla/.next/server/chunks/node_modules_927e2a._.js:2063:22)
    at [project]/node_modules/next-runtime-env/build/provider/index.js [app-route] (ecmascript) (/blabla/.next/server/chunks/node_modules_927e2a._.js:2085:3)
    at instantiateModule (/blabla/.next/server/chunks/[turbopack]_runtime.js:520:23)
    at getOrInstantiateModuleFromParent (/blabla/.next/server/chunks/[turbopack]_runtime.js:572:12)
    at commonJsRequire (/blabla/.next/server/chunks/[turbopack]_runtime.js:136:20)
    at Object.<anonymous> (/blabla/.next/server/chunks/node_modules_927e2a._.js:2434:14)
    at [project]/node_modules/next-runtime-env/build/index.js [app-route] (ecmascript) (/blabla/.next/server/chunks/node_modules_927e2a._.js:2444:3)
    at instantiateModule (/blabla/.next/server/chunks/[turbopack]_runtime.js:520:23)

it works fine for me if I use next.js 14.1

I found that next.js swear on import { createContext } from 'react'; and asks to add 'use client' for it. Maybe the reason is somewhere around.

It does not read values when I reload a page of a subroute

Whenever I have a subroute, for example user/details and I manually reload the page, the app breaks because it cannot find .env values.

I am using PublicEnvScript as suggested and I have all my vars with the NEXT_PUBLIC_ prefix:

import { PublicEnvScript } from 'next-runtime-env';
...
return (





{children}


);

Anyone able to help pls?

Versions:
"next": "^14.2.2",
"next-runtime-env": "^3.2.1",
"react": "^18.2.0",

How to set this up with a multi-stage docker built and using node server.js

When following the Docker build that Vercel recommends here (https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile), they use a multi stage build and runs node server.js when it starts.

Because of this, next-runtime-env does not execute and doesn't generate the __ENV.js file that is needed.

Not sure if there's some way make this work like https://github.com/kHRISl33t/runtime-env-cra did for the create-react-app projects.

Next-Cloudinary still cannot access NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME

I have properly set-up the in the root layout, and I have properly set the environment variable in running a container, but I still get this error
Error: A Cloudinary Cloud name is required, please make sure NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME is set and configured in your environment.

But in my .env file where I use with docker compose to run a container, I have already set it there

NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_bmVhdC1wYW5kYS0xMi5jbGVyay5hY2NvdW50cy5kZXYk
NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME="cloudnamehere"

The cloud name works in development

Also, when I build the NextJs application with a NEXT_CLOUDINARY_CLOUD_NAME variable, I do not get an error, but when I put a different value for that variable in running a container, it still uses the old variable, so in essence, it is not able to read the variable I put at run-time

questions about makeEnvPublic and EnvScript

Hi, thank you for creating this library. I have a few small questions I'd like to clarify.

makeEnvPublic seems to be used when you want to expose some server variables to the public.
So, you can use makeEnvPublic('FOO') and then in the client component use env('NEXT_PUBLIC_FOO').

My question is, can't we achieve the same effect directly with EnvScript like this:

<EnvScript
  env={{
    NEXT_PUBLIC_FOO: process.env.FOO,
  }}
/>

And then in the client component just env('NEXT_PUBLIC_FOO')

So, why do we still need makeEnvPublic ?

is V1 support getStaticProps runtime variable ?

version: 1.7.4

reproduce repo: https://github.com/aNyMoRe0505/runtime-env-test

steps: clone -> npm ci -> npm run build -> npm run start -> open localhost:3000/client-side

Thank you for creating this repo.
I'd like to ask if getStaticProps supports runtime environment variables.
My understanding is that variables need to be determined during the build, making it challenging to achieve Build once, deploy many.

However, I noticed that version 1 supports getStaticProps, so I'm wondering if I've set something up incorrectly. Thank you.

"Env" utility does not support custom variables

Although a way is provided to define custom variables via script (without the NEXT_PUBLIC prefix), the supported way of accessing those variables throws an error.

To allow for custom variables via script, we must use EnvScript. However, when trying to access those variables using the env function, we get an error. The env function is written to throw an error if the variable does not start with NEXT_PUBLIC_, so the only way to access our variables is with a workaround via window.__ENV, which is not future proof.

Am I interpreting usage incorrectly, or is it possible to get an update to allow better usage of custom variables in the recommended way? Thank you!

Issue when working with route.ts

Package versions

  • next-runtime-env: 2.0.0-alpha.3
  • next versions:
    • 13.5.5
    • 13.5.6
    • 14.0.0

Issue

I am running into an issue using this package with routes:

//app/api/v1/companies/route.ts
export async function GET(request: NextRequest) {
  return Response.json({ foo: process.env.NEXT_PUBLIC_BAR })
}

export const dynamic = 'force-dynamic'

This is still returning the build time environment variables instead of the runtime environment variables. Am I doing something wrong?

How to use env variables in the middleware?

The package claims to work with the middleware.

Though, in my experience (see below), I could not get it to work. Considering the middleware is an Edge runtime, that probably makes sense. Is there some other mechanism to support this use case?


SERVER_ENV=server NEXT_PUBLIC_ENV=client_server next dev
import { env } from "next-runtime-env";
import { NextRequest, NextResponse } from "next/server";

export async function middleware(req: NextRequest) {
  console.log("SERVER_ENV", env("SERVER_ENV));
  console.log("NEXT_PUBLIC_ENV", env("NEXT_PUBLIC_ENV"));

[...]
}

question about injecting environment variable thorugh docker run --env

Hi, I am really suffering from trying to inject environment varaible through docker run --env and i found your package.

In Next JS, I tried

const temp - () = > {
const { NEXT_PUBLIC_FOO } = useEnvContext();
console.log(NEXT_PUBLIC_FOO );
};
export default temp;

and did docker run XXX --env NEXT_PUBLIC_FOO=hi

but console.log still prints undefined.... I dont think it recognizes my runtime environment variable injected from docker run --env.

Is there any solution?

Thank you!! please help me !!!

Using Cypress will cause Hydration Problems.

Hello!
I have been trying to implement Cypress E2E testing in my application that relies on next-runtime-dev. I am using the Next.j 14 with the App Router.
I don't normally get any issues, but whenever I load up my website in the Cypress controlled browser (I tried Chrome and Edge) I will get this error: https://gist.github.com/gripzyyy/3f0e314c5de2aafa5be7342300106eba
Because of this I can not run any cypress tests. Deleting the element from my layout that has the PublicEnvScript will remove that error. I have tried using supressHydrationWarning but it won't work. There is no support from Next.js regarding how to fully ignore this error also.

The automated release is failing 🚨

🚨 The automated release from the 1.x.x branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the 1.x.x branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The release 1.7.1 on branch 1.x.x cannot be published as it is out of range.

Based on the releases published on other branches, only versions within the range >=1.7.0 <1.7.0 can be published from branch 1.x.x.

The following commits are responsible for the invalid release:

  • ci: πŸ”– set proper depth for maintenance branch (3dc48f0)
  • ci: πŸ”– support building maintenance releases (db46ef1)
  • docs: ⬆️ upgrade examples (15c1a10)
  • docs: πŸ“š reference v2 in readme (088ba74)
  • ci: βœ… run tests on node version 18 and 20 (f8d14eb)
  • build: ⬆️ upgrade deps (5f09c2a)
  • ci: πŸ‘· upgrade actions/checkout to v4 (e824da3)
  • ci: πŸ‘· remove dependabot in favour of snyk (29a2e5b)

Those commits should be moved to a valid branch with git merge or git cherry-pick and removed from branch 1.x.x with git revert or git reset.

A valid branch could be main.

See the workflow configuration documentation for more details.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

πŸ“£ Dropping support for Page Router in version 2.x

From version 2.x onwards, we plan only to support the App Router as the solution is fundamentally different. (No longer uses the _ENV.js file in the public folder.)

We're supporting the Page Router on the 1.x branch. We will keep pushing security updates and keep accepting pull requests for it. (Our company still has some front-ends depending on it πŸ™‚)

Support loading custom config files

Thank you for this package it solves one consistent frustration I've had with Next.js!

We have a config file that gets written to the image at start up and we would like to make it available in the browser in the same way you have made the environment available. My idea is to add an additional public file __CONFIG.js that will add the config to the window and add a function config() that will return that config both client side and server side.

// __CONFIG.js

window.__CONFIG={"foo": "bar", "list":["foo", "bar"]}

Ideally this solution would support config files written in json, yml, js, or ts.

I've only looked into the v1.x.x implementation so far as we are still on the page directory, but I suppose we could do something similar with providers for v2.x.x.

If you're interested I would be happy to contribute this feature.

✨ Next.js 13 - App Router Support

This issue is an overarching ticket to track the App Router support.

  • Support client components reading environment variables at runtime.
  • Support server components reading environment variables at runtime. (See: #35)
  • Fix client-side hydration.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.