---
title: Variables in package.json
date: 2018-10-31
tags: npm, variables, package.json
source: https://brianchildress.co/blog/variables-in-package-json
---

# Variables in package.json

As a general rule of thumb, anytime I have to declare something more than a couple of times or change a value regularly I look to create a variable to hold that value. It helps me to be consistent and reduce errors. It's not often but sometimes my _package.json_ could benefit from variables. Here's how you can add variables to your _package.json_.

Let's start with a simple _package.json_ file.

_package.json_
```json
{
  "name": "my-test-app",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "client": "URL=http://192.168.1.120 PORT=9092 node client.js",
    "server": "URL=http://192.168.1.120 PORT=9092 node server.js"
  },
  "author": "joe bag",
  "license": "ISC"
}
```

I have two _npm script_ commands that help me start a node process. Both commands pass the same `URL` and `PORT` environment variables. Since the values are the same and could potentially change in the future I want to abstract those into variables. To do that we can create a separate object in our _package.json_ to hold the values called `config`. That object looks something like this:

_package.json_
```json
...
  "config": {
    "port": "9092",
    "url": "192.168.1.120"
}
```

To reference the variable contained in our new `config` object we need to first append `$npm_package_` to the reference, then using `_` we call drill down to the individual nested values. For example, to reference the `port` value we would call `$npm_package_config_port`.

Let's take a look at the new _package.json_ with the variables being used.

_package.json_
```json
{
  "name": "my-test-app",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "client": "URL=http://$npm_package_config_url PORT=$npm_package_config_port node client.js",
    "server": "URL=http://$npm_package_config_url PORT=$npm_package_config_port node server.js"
  },
  "author": "joe bag",
  "license": "ISC",
    "config": {
      "port": "9092",
      "url": "192.168.1.120"
  }
}
```
