how can I use an environment variable to specify the base color in my CSS ?
I use NEXTJS
My colors are all defined as variables in my globals.css :
@layer base {
:root {
...
--primary: #0096d0;
--primary-bright: hsl(from var(--primary) h s calc(l*1.5));
...
I tried
--primary: env(NEXT_PUBLIC_PRIMARY_COLOR, #0096d0);
But the env variable is ignored
Any idea ?
While
env()does work with custom properties, it reads from UA-defined environment variables, not from the publishedNEXT_PUBLIC_variables in the client-side, and definetly not server-side environment variables. Though in the future we might be able to add custom environment variables via JS or CSS, currently you can't define client-side Custom CSS Environment Variables yet.Hence, for now you will need to either consider using CSS preprocessors, inline-styles in JSX, or PostCSS plugins. They all have their own drawbacks.
Inline Styles
The main disadvantage is that this can't be used in the global.css like you were. However, the advantage is that you can create the
styleobject however you want. You can also update thestyleobject and trigger an update after the app is running. (Note that allNEXT_PUBLIC_variables will be frozen from being updated during runtime.)In
index.js:CSS Preprocessors
Following is an example setup to import specific environment variables into scss variables.
First, follow the Next document Styling with SCSS to install SASS:
In
next.config.js, prepend the SASS variables:In
.env.local:Then you can use the environment variables in
globals.scssby:The drawback is that SCSS is "preprocessed", means that the SCSS variables also don't exist for you to update during JS runtime. Also, the environment variable have to always be presented, or else you need to use
variable-exists()or!defaultexplicitly, which is somewhat verbose. For example:PostCSS Plugins
Since you are using Nextjs, PostCSS and some plugins are built-in already. However, currently none of the built-in ones matches your need. You need to find a plugin or implement one that solves your problem.
One example is the postcss-functions plugin that allows you define you own env function that reads from environment variables.
In
postcss.config.js:Then you can use it in global.css as follow: