File tree Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1193 TILs and counting..._
13
+ _ 1194 TILs and counting..._
14
14
15
15
---
16
16
@@ -521,6 +521,7 @@ _1193 TILs and counting..._
521
521
522
522
- [ Create Files And Directories For Dynamic Routes] ( nextjs/create-files-and-directories-for-dynamic-routes.md )
523
523
- [ 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 )
524
525
- [ Push A Route With A URL Object] ( nextjs/push-a-route-with-a-url-object.md )
525
526
- [ Remove A Query Param From The URL] ( nextjs/remove-a-query-param-from-the-url.md )
526
527
- [ Ship Public Assets With A Next.js App] ( nextjs/ship-public-assets-with-a-nextjs-app.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments