diff --git a/README.md b/README.md index f1cca12..3a7b22d 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/nextjs/make-environment-variable-publicly-available.md b/nextjs/make-environment-variable-publicly-available.md new file mode 100644 index 0000000..f98701d --- /dev/null +++ b/nextjs/make-environment-variable-publicly-available.md @@ -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)