mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Make Environment Variable Publicly Available as a Next.js TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1193 TILs and counting..._
|
||||
_1194 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -521,6 +521,7 @@ _1193 TILs and counting..._
|
||||
|
||||
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
|
||||
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
|
||||
- [Make Environment Variable Publicly Available](nextjs/make-environment-variable-publicly-available.md)
|
||||
- [Push A Route With A URL Object](nextjs/push-a-route-with-a-url-object.md)
|
||||
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)
|
||||
- [Ship Public Assets With A Next.js App](nextjs/ship-public-assets-with-a-nextjs-app.md)
|
||||
|
||||
40
nextjs/make-environment-variable-publicly-available.md
Normal file
40
nextjs/make-environment-variable-publicly-available.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# Make Environment Variable Publicly Available
|
||||
|
||||
You can define environment variables in `.env.development` and
|
||||
`.env.production` files for use in your app. This is a great way to seamlessly
|
||||
swap out values that are specific to each environment.
|
||||
|
||||
For instance, you might have a base URL for API requests that points to a local
|
||||
server in development and then to the live server in production.
|
||||
|
||||
You could define that value like so:
|
||||
|
||||
```
|
||||
API_BASE_URL=localhost:3000/api/v1
|
||||
```
|
||||
|
||||
The problem you'll quickly run into is in trying to access that value from any
|
||||
client-side pages or components.
|
||||
|
||||
```
|
||||
process.env.API_BASE_URL //=> undefined
|
||||
```
|
||||
|
||||
Next.js is trying to help us out here. Environment variables are often times
|
||||
private keys and other secrets that shouldn't be bundled into our public client
|
||||
code. So Next.js excludes all env vars from the build by default.
|
||||
|
||||
Our API's base URL is not a secret though. The way to make env vars like that
|
||||
publicly avilable is to prepend them with `NEXT_PUBLIC_`.
|
||||
|
||||
```
|
||||
NEXT_PUBLIC_API_BASE_URL=localhost:3000/api/v1
|
||||
```
|
||||
|
||||
Now, it is available anywhere in your client and server code:
|
||||
|
||||
```
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL //=> 'localhost:3000/api/v1'
|
||||
```
|
||||
|
||||
[source](https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser)
|
||||
Reference in New Issue
Block a user