Skip to content

Commit 2ac7486

Browse files
committed
Add Make Environment Variable Publicly Available as a Next.js TIL
1 parent 9b17d8b commit 2ac7486

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1193 TILs and counting..._
13+
_1194 TILs and counting..._
1414

1515
---
1616

@@ -521,6 +521,7 @@ _1193 TILs and counting..._
521521

522522
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
523523
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
524+
- [Make Environment Variable Publicly Available](nextjs/make-environment-variable-publicly-available.md)
524525
- [Push A Route With A URL Object](nextjs/push-a-route-with-a-url-object.md)
525526
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)
526527
- [Ship Public Assets With A Next.js App](nextjs/ship-public-assets-with-a-nextjs-app.md)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Make Environment Variable Publicly Available
2+
3+
You can define environment variables in `.env.development` and
4+
`.env.production` files for use in your app. This is a great way to seamlessly
5+
swap out values that are specific to each environment.
6+
7+
For instance, you might have a base URL for API requests that points to a local
8+
server in development and then to the live server in production.
9+
10+
You could define that value like so:
11+
12+
```
13+
API_BASE_URL=localhost:3000/api/v1
14+
```
15+
16+
The problem you'll quickly run into is in trying to access that value from any
17+
client-side pages or components.
18+
19+
```
20+
process.env.API_BASE_URL //=> undefined
21+
```
22+
23+
Next.js is trying to help us out here. Environment variables are often times
24+
private keys and other secrets that shouldn't be bundled into our public client
25+
code. So Next.js excludes all env vars from the build by default.
26+
27+
Our API's base URL is not a secret though. The way to make env vars like that
28+
publicly avilable is to prepend them with `NEXT_PUBLIC_`.
29+
30+
```
31+
NEXT_PUBLIC_API_BASE_URL=localhost:3000/api/v1
32+
```
33+
34+
Now, it is available anywhere in your client and server code:
35+
36+
```
37+
process.env.NEXT_PUBLIC_API_BASE_URL //=> 'localhost:3000/api/v1'
38+
```
39+
40+
[source](https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser)

0 commit comments

Comments
 (0)