Using Environment Variables in a Frontity project
Last updated
Was this helpful?
Last updated
Was this helpful?
Environment variables are a very useful way of managing custom data that shouldn't be in the code. A prime example would be API KEYs or other authentication credentials for external APIs.
Since a we need to consider whether these environment variables should be accessible only to the code running server-side, or whether they should also be accessible to the code running client-side.
In order to access environment variables from your Frontity project you can use a package such as or .
If you use cross-env
, you will not have to do anything special in Frontity. You just need to add it to your package.json
scripts thus:
dotenv
only runs in Node, so rather than using an index.js
file you should instead .
So for dotenv
we must create a .env
file:
The content of the server.js
file could be something like this:
In this example a API_TMDB
environment variable is defined in a .env
file included in that project
If you need to use the ENV variable also in the client, the best way is to add it to the state
.
You can use frontity.settings.js
or your package state
for that, whichever is more appropriate for your situation.
frontity.settings.js
:
packages/my-package/src/server.js
:
Either way, the ENV variable will be serialized with the rest of the state
and it will be sent to the client for the React hydration.
Please note that any ENV variable exposed in state
will end up in the client. Do not expose any secret API KEY or password.
As for our Frontity theme package by creating separate server.js
and client.js
files (that will each only be executed in the appropriate environment), we are therefore able to privately access the content of the environment variable on the server (for example to perform a request to an external API and storing this data in the state
so it can be accessed from your React components).
illustrating the use of an environment variable in server.js
.
This method (beforeSSR
defined in the server.js
) will ensure that your API credentials are secure (i.e. they will not be part of the client bundle) and are only visible to the code running server-side. However, remember to take into account that this logic will be executed in the (i.e. for any page loaded the first time).