Best practices for creating a modern npm package
Tags: javascript, node, typescript
Published: 2022-09-12 21:03:49

---
title: Best practices for creating a modern npm package
published: true
date: 2022-09-12 01:53:05 UTC
tags: JavaScript, Nodejs, typescript
canonical_url: https://snyk.io/blog/best-practices-create-modern-npm-package/
---

Technology is always changing and your processes and practices need to keep up with those changes. So while npm is 12 years old, your practices around npm package creation should _hopefully_ be a lot more modern. If you have a feeling they may be a little out of date, though, keep reading. 

In this tutorial, we’re going to walk step by step through creating an npm package using modern best practices (as of 2022). You will first learn how to create an npm package, so you can get familiar with building and publishing a package to the npm registry. Then you’ll learn what’s involved with making a more robust and production-ready npm package by setting up a test framework, a continuous integration and deployment pipeline, security checks, and automated semantic version management for release. By the end of this tutorial, you’ll feel confident in your ability to produce modern and sustainable npm packages. Let’s get started!

## Prerequisites

1. Familiarity with Node.js, JavaScript, GitHub, and GitHub Actions
2. Development tools available to assist with creating an npm package

## Simple example npm package

Let’s first get acquainted with the process of creating and publishing an npm package by using a simple example. If you’re already familiar with this you can jump ahead to the [Production-ready npm package](#prod-ready) section which covers more advanced topics.

### Set up your project

You’ll need a project in GitHub to get started, so follow these steps to initiate a project. If you already have one to use, you can skip to the next section, but **be sure to double-check step 5 in this section** regarding your package name.

1. Create a GitHub repository: [`https://github.com/new`](https://github.com/new)
2. Clone the repo locally.  
**Example:** `git clone https://github.com/snyk-labs/simple-npm-package.git`
3. Open your terminal and change directories to the folder of your cloned project.  
**Example:** `cd simple-npm-package`
4. Run `npm init -y` to create a `package.json` file. **Note:** If you cloned the example repository, you won’t need to do this step.
5. Update the `name` property in `package.json` with a scoped name.  
**Example:** `@snyk-labs/simple-npm-package`. Be sure to use your username or organization name instead of `@snyk-labs`.
6. Write your code for the package (or just use the hello world example in index.js).

Once your project is created, you can move on to creating an npm account. Through the rest of this tutorial, you’ll see that I’m working on a local clone (`clarkio/simple-npm-package`) of the repo.

### Set up an npm account

In order to be able to make your npm package available for others to use, you’ll need an npm account. The following steps will walk you through creating your own account (if you don’t have one already), enabling two-factor authentication (2FA) to improve the security of your account, and connecting your account to your local machine.

1. Sign up with npm at [https://www.npmjs.com/signup](https://www.npmjs.com/signup). 
2. For better security, enable 2FA on your npm account: [https://docs.npmjs.com/configuring-two-factor-authentication](https://docs.npmjs.com/configuring-two-factor-authentication) 
3. Sign in with your npm account in your terminal using the command `npm login` and follow the on-screen instructions:

```
> npm login
npm notice Log in on https://registry.npmjs.org/
Username: clarkio
Password:
Email: (this IS public) <email address>
npm notice Please use the one-time password (OTP) from your authenticator application
Enter one-time password from our authenticator app: <OTP>
Logged in as clarkio on https://registry.npmjs.org/.
```

### How to publish your npm package

Once you have an npm project and an npm account, you’re ready to publish your npm package to the [public and official npmjs registry](https://npmjs.org/) to make it available for others to consume. Here are the steps for you to follow to check what will be published before executing that and then running the actual publish process:

1. In your terminal, run `npx npm-packlist` to see the contents that will be included in the published version of the package.   
  
This ensures you are not missing any source code files that are needed for your package to function properly. It’s also a good practice to make sure you aren’t accidentally leaking sensitive information to the public such as a local configuration file with database credentials or API keys.

```
> npx npm-packlist
LICENSE
index.js
package.json
README.md
```

2. In your terminal, run `npm publish --dry-run` to see what would be done when actually running the command.

```
> npm publish --dry-run
npm notice
npm notice 📦@clarkio/simple-npm-package@0.0.1
npm notice === Tarball Contents ===
npm notice 1.1kB LICENSE
npm notice 1.2kB README.md
npm notice 95B index.js
npm notice 690B package.json
npm notice === Tarball Details===
npm notice name: @clarkio/simple-npm-package
npm notice version: 0.0.1
npm notice filename: @clarkio/simple-npm-package-0.0.1.tgz
npm notice package size:	1.7 kB
npm notice unpacked size: 3.1 kB
npm notice shasum: 40ede3ed630fa8857c0c9b8d4c81664374aa811c
npm notice integrity: sha512-QZCyWZTspkcUXL... ]L60ZKBOOBRLTg==
npm notice total files: 4
npm notice
+ @clarkio/simple-npm-package@0.0.1
```

3. In your terminal, run `npm publish --access=public` to actually publish the package to npm. **Note:** `--access=public` is needed for scoped packages (@clarkio/modern-npm-package) as they’re private by default. If it’s not scoped and doesn’t have the private field set to `true` in your `package.json`, it will be public as well.

```
> npm publish --access=public
npm notice
npm notice 📦@clarkio/simple-npm-package@0.0.1
npm notice === Tarball Contents ===
npm notice 1.1kB LICENSE
npm notice 1.2kB README.md
npm notice 95B index.js
npm notice 690B package.json
npm notice === Tarball Details===
npm notice name: @clarkio/simple-npm-package
npm notice version: 0.0.1
npm notice filename: @clarkio/simple-npm-package-0.0.1.tgz
npm notice package size:	2.1 kB
npm notice unpacked size: 4.1 kB
npm notice shasum: 6f335d6254ebb77a5a24ee729650052a69994594
npm notice integrity: sha512-VZ1K1eMFOKeJW[...]7ZjKFVAxLcpdQ==
npm notice total files: 4
npm notice
This operation requires a one-time password.
Enter OTP: <OTP>
+ @clarkio/simple-npm-package@0.0.1
```

You’re done! You’ve completed building and deploying your own npm package. Next up, you’ll learn how to make a more robust package that is ready for production environments and to be used more widely.

## Production-ready npm package

While the previous example package could potentially be used in production, it involves manual work to keep up with its maintenance over time. Using tools and automation along with proper testing and security checks will help minimize the total effort to keep the package running smoothly. Let’s dive deeper to see what that involves.

The following sections will cover:

1. Set up your `modern-npm-package` project
2. Building for both CommonJS (CJS) and ECMAScript (ESM) module formats
3. Setting up and writing unit tests
4. Implementing security checks
5. Automating version management and publishing

If you don’t have your own project to use while following along with this article, you can use the following example project as a reference: [https://github.com/](https://github.com/snyk-labs/modern-npm-package)[snyk-labs](https://github.com/snyk-labs/modern-npm-package/blob/main/tests/index.spec.ts)/modern-npm-package

### Set up your project

You’ll need a project in GitHub to get started, so follow these steps to initiate a project. If you already have one to use, you can skip to the next section, but **be sure to double-check step 5 in this section** regarding your package name.

1. Create a GitHub repository: [`https://github.com/new`](https://github.com/new)
2. Clone the repo locally.  
**Example:** `git clone https://github.com/snyk-labs/simple-npm-package.git`
3. Open your terminal and change directories to the folder of your cloned project.  
**Example:** `cd modern-npm-package`
4. Run `npm init -y` to create a `package.json` file. **Note:** If you cloned the example repository, you won’t need to do this step.
5. Update the `name` property in `package.json` with a scoped name.  
**Example:** `@snyk-labs/modern-npm-package`. Be sure to use your username or organization name instead of `@snyk-labs`.
6. Write your code for the package (or just use the hello world example in index.js).

Once your project is created, you can move on to creating an npm account. Through the rest of this tutorial, you’ll see that I’m working on a local clone (`clarkio/modern-npm-package`) of the repo.

### Building for both CommonJS and ECMAScript Module Formats

While the ECMAScript Module format is now natively supported in Node.js as of version 12+,  it’s not quite widely adopted by the community yet. In an effort to be future proof and support both formats, you’ll see how using TypeScript can prepare your npm package for them.

1. First, create a base TypeScript configuration file with the name `tsconfig.base.json`. This is for common compilation settings that can be used regardless of which module format you’re targeting. Feel free to adjust these as needed for your project and in particular you’ll want to adjust the `files` property to align with your project structure if you’re not using the example one provided.

```
{
  "compilerOptions": {
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true,
    "checkJs": true,
    "allowJs": true,
    "declaration": true,
    "declarationMap": true,
    "allowSyntheticDefaultImports": true
  },
  "files": ["../src/index.ts"]
}
```

2. Then create a TypeScript configuration file for the CommonJS format and name it `tsconfig.cjs.json`.
  - The `lib` property indicates to TypeScript what types it should reference to assist you while writing code for your project.
  - The `target` property indicates to TypeScript which JavaScript version to compile your project code.
  - The `module` property indicates to TypeScript which JavaScript module format should be used when compiling your project code.
  - The `moduleResolution` property helps TypeScript to figure out how an “import” statement should be referred to.
  - The `outDir` and `declarationDir` properties indicate to TypeScript where to place the results from compiling your code and defining the types used within it.

```
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "lib": ["ES6", "DOM"],
    "target": "ES6",
    "module": "CommonJS",
    "moduleResolution": "Node",
    "outDir": "../lib/cjs",
    "declarationDir": "../lib/cjs/types"
  }
}
```

3. After that, create a TypeScript configuration file for the ECMAScript format and name it `tsconfig.esm.json`. The properties here are the same as what you saw in the CommonJS configuration, but now targeting the modern ECMAScript module format as its output.

```
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "lib": ["ES2022", "DOM"],
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "outDir": "../lib/esm",
    "declarationDir": "../lib/esm/types"
  }
}
```

4. Update your `package.json` file with a `files` field that points to your `lib` folder holding the results from TypeScript building the package for you.
5. Update your `package.json` file with an `exports` field to define how to find the source files based on the module loader in use (CJS vs. ESM). You can read more about this `exports` field support in the [Node.js documentation](https://nodejs.org/api/packages.html#packages_exports).  

```
"exports": {
    ".": {
      "import": {
        "types": "./lib/esm/types/index.d.ts",
        "default": "./lib/esm/index.mjs"
      },
      "require": {
        "types": "./lib/cjs/types/index.d.ts",
        "default": "./lib/cjs/index.js"
      }
    }
  },
```

6. Update your `package.json` file `main` and `types` fields to point to the CJS versions of the package. This is to act as a default, fallback, option.

```
“types": "./lib/cjs/types/index.d.ts",
"main": "./lib/cjs/index.js",
```

7. Add a `files` field to your `package.json` file to indicate which files should be included when npm packages up your code for publishing.

```
"files": [
   "lib/**/*"
],
```

8. Create commands via the `scripts` field in `package.json` to use `tsc` and compile both the CJS and ESM formats of the package. This will result in generating the source files for the `lib` folder.
  - The `clean` script is used to delete the output from past builds and start from a clean slate.
  - The `mv lib/esm/index.js lib/esm/index.mjs` at the end of the `build:esm` script renames the file extension so that the Node.js module loader knows it’s an ESM module.
  - The `prepack` script is used by npm before packing the npm package in preparation for publishing to a registry.

```
    "clean": "rm -rf ./lib",
    "build": "npm run clean && npm run build:esm && npm run build:cjs",
    "build:esm": "tsc -p ./configs/tsconfig.esm.json && mv lib/esm/index.js lib/esm/index.mjs",
    "build:cjs": "tsc -p ./configs/tsconfig.cjs.json",
    "prepack": "npm run build"
```

9. Now you can run `npm run build` in your terminal to have TypeScript build your project in preparation for use and publishing

That’s all the setup you need to do to use TypeScript for building your npm package that supports both the CommonJS and ECMAScript module formats. Next, you’ll learn how to set up and run tests against your npm package code to ensure it produces the results you expect.

### Setting up and adding tests

In order to have confidence in the behavior and results of your code, you will need to implement a testing process. Tests force you to think about the functionality of your code in different ways outside of the typical, happy, path when first creating it. As an example you can think of ways to break a function to cause it to throw an error or produce a result that’s not intended. Doing this will make your application more resilient and sustainable as well as ensure nothing breaks when adding more to it.

If you’d like to dive deeper into testing and learn about the best practices for it, be sure to read through Yoni Goldberg’s [JavaScript Best Practices repository](https://github.com/goldbergyoni/javascript-testing-best-practices).

### Unit Testing

Making sure your package behaves in the way you want it to involves writing tests against your code. You’ll need a few tools to help with setting up your project to run unit tests and show the results. These tools are Mocha.js, Chai.js and ts-node. [Mocha.js](https://mochajs.org/) is a test runner, [Chai.js](https://www.chaijs.com/) is an assertion library to help determine if you’re getting the results you’re expecting from your code, and [ts-node](https://www.npmjs.com/package/ts-node) helps us to use these tools in TypeScript projects. Follow the steps below to set up and run tests for your npm package:

1.  Install developer dependencies using the following command in your terminal:   
`npm i -D mocha @type/mocha chai @types/chai ts-node`
2. Create a new file `.mocharc.json` in the root directory of your project with the following contents:

```
{
     "extension": ["ts"],
     "spec": "./**/*.spec.ts",
     "require": "ts-node/register"
}
```

3. Create a `tests` folder in the root directory of your project.
4. Create an `index.spec.ts` file in the `tests` folder.
5. Write unit tests in the `index.spec.ts` file to test the code in `index.ts`. **Note:** You can refer to the example npm package repository as an example: [https://github.com/snyk-labs/modern-npm-package/blob/main/tests/index.spec.ts](https://github.com/snyk-labs/modern-npm-package/blob/main/tests/index.spec.ts)

6. Add a `test` property in the `scripts` section of your `package.json` file and give it a value of `mocha`.

```
  "scripts": {
    "clean": "rm -rf ./lib",
    "build": "npm run clean && npm run build:esm && npm run build:cjs",
    "build:esm": "tsc -p ./configs/tsconfig.esm.json && mv lib/esm/index.js lib/esm/index.mjs",
    "build:cjs": "tsc -p ./configs/tsconfig.cjs.json",
    "prepack": "npm run build",
    "test": "mocha"
  },
```

7. Run `npm test` in your terminal from the root folder of the project to execute your tests and see the results:

```
bc@mbp-snyk modern-npm-package % npm test

> @clarkio/modern-npm-package@0.0.0-development test
> mocha

  NPM Package
    ✔️ should be an object
    ✔️ should have a helloworld property

  Hello World Function
    ✔️ should be a function
    ✔️ should return the hello world message

4 passing (22ms)
```

### Testing in a pipeline

Now that you have tests to validate the behavior of your code you can use them in a pipeline. This will help to make sure no changes introduced into your repository will break your code behavior. Follow the steps below to create a test workflow as part of your project pipeline.

1. Create a new GitHub Action for your repository: `https://github.com/<your-account-or-organization>/<your-repo-name>/actions/new`
2. Rename the workflow to `tests.yml`
3. Insert the following Snyk Action script in your workflow file:

```
name: Tests

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [12.x, 14.x, 16.x, 18.x]

    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm ci
      - run: npm test
```

This YAML script checks out your latest code, installs its dependencies, and runs the `npm test` command to execute your tests. It does this for every version of Node.js listed in the `node-version` field so you can ensure the code works as expected in each runtime.

You’ve now finished setting up your project for running and evaluating tests against the code of your npm package. However, you may be thinking “how do I test _using_ my npm package in another project?” Let’s see how you can go about accomplishing that next.

### Package testing

It’s one thing to have confidence in the code of your npm package through unit tests, but it’s another thing to ensure the experience in using the overall npm package. This involves pulling in your npm package as a dependency into another project and seeing if its use there goes as smoothly as you expect it to. Here are five ways you can test this:

1. Install via `npm pack` output
2. Install via relative path
3. Install via `npm link`
4. Install via registry (such as the npm public registry at [npmjs.com](https://npmjs.com))
5. Use [Verdaccio](https://verdaccio.org/) (an open source npm private npm registry project) to run end-to-end package publishing and install steps as part of your CI

#### npm pack

This approach will leverage the `npm pack` command to package up and zip your npm package into a single file (`<package-name>.tgz`). You can then go to the project you want to use the package in and install it via this file. The steps to do this are as follows:

1. From within your npm package directory, run `npm pack` in your terminal. Note the .tgz file it produces and the location of it.
2. Change directories to the project directory where you want to use the npm package. **Example:** `cd /path/to/project`
3. From within the **client** project directory, run `npm install /path/to/package.tgz` but replace it with the proper path to the location of the .tgz file from step 1
4. Then you can start using the package in that **client** project to test things out

This will give you the closest to production experience for using your npm package.

#### npm link

This approach will leverage the `npm link` command to point to your package directory when attempting to install it in **client** projects. The steps to do this are as follows:

1. From within your npm package directory run `npm link` in your terminal
2. Change directories to the project directory where you want to use the npm package.   
**Example:** `cd /path/to/project`
3. From within the **client** project directory run `npm link <name-of-your-package>`

This will point your **client** project to the npm package directory when referencing the package for use in your code. This doesn’t give you a full production-like experience for the use of your package, but does allow you to ensure the functionality works as expected.

#### Relative path

This approach leverages your existing knowledge of using the `npm install` command. It’s similar to `npm link` without having to know a new command like `link`.

1. From within your **client** project directory run `npm install /path/to/your/package` in your terminal.

Similar to the `npm link` approach, this will allow you to quickly test the functionality of your package within a client project but will not give you the full production-like experience. This is because it points to the full package source code directory and _not_ a built version of the package that you’d find in an npm registry.

#### npm registry

This approach leverages using the public (or your own) registry for npm packages. It involves publishing your package and installing as you typically would for any other npm package.

1. Publish your npm package using the steps outlined earlier in this article via the `npm publish` command
2. Change directories to the project directory where you want to use the npm package.   
**Example:** `cd /path/to/project`
3. From within the **client** project directory run `npm install <name-of-your-package>`

Shout out to Mirco Kraenz ([@MKraenz](https://twitter.com/MKraenz)) who created a [Twitter thread](https://twitter.com/MKraenz/status/1559188177696436226?s=20&t=LJg1FbyDLTmiOGAUQh7LmQ) summarizing our learnings of this during a livestream!

At this point, you’ve now built your package to support modern module formats and ensured it’s behaving as expected through unit tests and packaging tests. Next, you’ll need to make sure there aren’t any security issues and prevent new ones from being introduced in your npm package.

## Implementing security checks

In the same way you don’t want security vulnerabilities in your own projects, you also don’t want to introduce vulnerabilities into anyone else’s project. Building an npm package expected to be used within many other projects presents an increased level of responsibility to ensure things are secure. You need to have security checks in place to help monitor for, alert on, and offer assistance to mitigate vulnerabilities. This is where a tool like [Snyk](https://app.snyk.io) can simplify the work needed to accomplish these needs.

For this example npm package, you’re using GitHub as your source control management tool so you’ll leverage its GitHub Actions feature to integrate Snyk in your workflow. Snyk has a [GitHub Actions](https://github.com/snyk/actions) reference project that helps jump start the work for this and offers examples for other programming languages and tools you might be using for your projects.

1. Snyk is free, so sign-up and get your [Snyk API Token](https://app.snyk.io/account).
2. Add your Snyk API Token as a Repository Secret on GitHub: https://github.com/<your-account-or-organization>/<your-repo-name>/settings/secrets/actions/new
3. Create a new GitHub Action for your repository: [https://github.com/](https://github.com/)<your-account-or-organization>/<your-repo-name>/actions/new
4. Rename the workflow to `snyk.yml`.
5. Insert the following Snyk Action script in your workflow file:

```
name: Snyk Security Check
on: [push,pull_request]
jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@main
      - name: Run Snyk to check for vulnerabilities
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
```

6. Commit your changes.
7. Validate the Action ran successfully: [https://github.com/](https://github.com/)<your-account-or-organization>/<your-repo-name>/actions

With this now set up, **anytime anyone pushes to your repository or opens a pull request against it, a security check will run** to ensure it’s not introducing any vulnerabilities into the package. If it does find an issue, the Action will fail and alert you with the details of the security issue found. Next up you’ll automate the process around versioning and publishing your npm package.

One thing to note about this current setup is that it’s only leveraging the [Snyk Open Source](https://snyk.io/product/open-source-security-management/) (SCA) product and not [Snyk Code](https://snyk.io/product/snyk-code) (SAST). Snyk Code is our code security product, and you’ll need to enable it (for free) via your Snyk account first and then add into your workflow script here to take full advantage of it. To learn more about using Snyk Code in your pipeline read this article on [Building a Secure Pipeline with GitHub Actions](https://snyk.io/blog/building-a-secure-pipeline-with-github-actions/) (it uses Java and Maven, but can be replaced with Node.js and npm).

## Automating version management and publishing

Whenever you merge changes in your main branch, you don’t want to manually update the version of the npm package and publish it every time. Instead, you’ll want to automate this process to happen for you. If you recall from the simple npm package example earlier in this post, you used the following commands to update the version of the npm package and then publish it:

```
npm version <major|minor|patch>
npm publish
```

You also want to follow the industry standard of semantic versioning so that consumers of your package understand what implications come with the different version changes you publish to the registry. 

### What is semantic versioning?

Semantic versioning prescribes that the version be numbered with three placeholders. The first being the major version, second being the minor version, and last being the patch version. To learn more about semantic versioning, version management and lockfiles read [What is Package Lock JSON and How a Lockfile Works with Yarn and NPM packages](https://snyk.io/blog/what-is-package-lock-json/)

What if you could skip doing all that manually and instead set up an automated workflow with GitHub Actions that handles npm package publishing for you? You’re in luck because there’s a tool available called [Semantic Release](https://semantic-release.gitbook.io/semantic-release/) which integrates with [GitHub Actions](https://semantic-release.gitbook.io/semantic-release/recipes/ci-configurations/github-actions). The key to help automate this process is that you use what’s called [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) while commiting changes to your project. This enables the automation to update everything accordingly and know how to prepare the next release of your project for you.

The following steps will walk you through setting this up for your modern npm package.

1. In your terminal, run: `npm i -D semantic-release`
2. In your terminal, run: `npx semantic-release-cli setup`
3. Follow the terminal prompts and provide the needed tokens:
  - You’ll need a personal access token from GitHub. To create one go to `https://github.com/<your-name-or-github-organization>/<your-repo-name>/settings/secrets/actions/new` but replace it with your respective repository details
  - While creating this token use the following scopes:

![A screenshot of the form on GitHub to create a new personal access token](https://snyk.io/wp-content/uploads/blog-create-npm-packages-new-token-1240x837.png)

4. You’ll also need an **Automation-type** access token from npm to be used solely in CI environments so that it is able to work around your account’s 2FA. To create one, go to [https://www.npmjs.com/settings/](https://www.npmjs.com/settings/)<your-npm-account>/tokens. Be sure to select the type “Automation” as this will be used in a CI/CD workflow.

![A screenshot of creating a new token on NPM](https://snyk.io/wp-content/uploads/blog-create-npm-packages-token-1240x1123.png)

```
bc@mbp-snyk modern-npm-package % npx semantic-release-cli setup
? What is your npm registry? https://registry.npmjs.org/
? What is vour npm username? clarkio
? What is your npm password? [hidden]
? What is your NPM two-factor authentication code? <2FA code>
Provide a GitHub Personal Access Token (create a token at https://github.com/settings/tokens/new?scopes=repo
<token>
? What CI are you using? Github Actions
bc@mbp-snyk modern-npm-package %
```

5. Add your npm token to your GitHub repository as a repository secret here: https://github.com/<your-name-or-organization/<your-repository>/settings/secrets/actions/new. Set the name of the secret as `NPM_TOKEN` with its value that you retrieved in an earlier step

![A screenshot of the form on GitHub to add a new environment variable for your NPM token](https://snyk.io/wp-content/uploads/blog-create-npm-packages-secret-1240x714.png)

6. Back in your project, go to your `package.json` file and add a `releases` key like below. If your repository’s primary branch is still called `master` and not `main` then update the above `branches` value accordingly.

```
"release": {
    "branches": ["main"]
  }
```

7. Add a `publishConfig` key in your `package.json` file as well:

```
"publishConfig": {
    "access": "public"
 }
```

8. Test everything out by doing a dry run using the `semantic-release` npm script. Take the following command and set the `NPM_TOKEN=` and `GH_TOKEN=` values to use your respective token values. Then copy and run the full command in your terminal to see if everything runs correctly. You’ll see the process logged to the output of your terminal. If any issues arise they’ll be visible here and offer details to resolve them.
9. After confirming the dry run completes successfully you can set up your GitHub repository with a new GitHub Action to handle the publishing process for you. Go to your repository on GitHub and click “Actions”
10. Click the **New workflow** option.
11. Rename the workflow to `release.yml`.
12. Add the below YAML script to the new workflow file. This script essentially says that once the Snyk Security Check work completes successfully, run the release job. The release job checks out the code, sets up a Node.js environment, installs your dependencies and then runs semantic release using your GitHub and npm tokens.

```
name: Release
on:
  workflow_run:
    workflows: ['Snyk Security Check', 'Tests']
    branches: [main]
    types:
      - completed

jobs:
  release:
    name: Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Setup Node.js
        uses: actions/setup-node@v2
        with:
          node-version: 'lts/*'
      - name: Install dependencies
        run: npm ci
      - name: Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npx semantic-release
```

13. Commit your local changes and push them to your GitHub repository
  - You can do this by running the command `git commit -am '<your commit message>'` in your terminal and then `git push`.
  - You can also do this in VS Code via its [version control functionality](https://code.visualstudio.com/docs/editor/versioncontrol).
14. With all of that set up, you can now use [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) to push changes to your main branch (or by merging pull requests) and the release workflow will run (after the Snyk Security Check of course). You can view an instance of that happening in the example [modern-npm-package repository workflow](https://github.com/clarkio/modern-npm-package/actions/runs/2886059078).

## Continuous security monitoring with Snyk via GitHub

While it’s beneficial to have security checks directly in the process where you commit your code there is potential to miss out on vulnerabilities that arise between commits. For instance, if you haven’t pushed any code to your repository in a few months you won’t know about any new vulnerabilities that were discovered in that time. This is where Snyk helps even more! When you connect your GitHub repository to Snyk, it will automatically monitor for new vulnerabilities and alert you to them regardless of how often you’re coding on the project. In addition to that, it will provide automated pull requests to address the security issues for you.

There are two products from Snyk which are particularly helpful for ensuring the security of your npm package code and its dependencies. [Snyk Code](https://snyk.io/product/snyk-code) assists with the security of your package code and [Snyk Open Source](https://snyk.io/product/open-source-security-management/) monitors your open source dependencies for vulnerabilities.

To get started taking full advantage of your free Snyk account, follow the steps below:

1. [Sign into your free Snyk account](https://app.snyk.io/login)
2. Choose **Add project** and then **GitHub**.

![A screenshot of adding a GitHub based project to the Snyk App](https://snyk.io/wp-content/uploads/blog-create-npm-packages-gh.png)

3. Search for your project’s repository by name and select the checkbox next to it.

![A screenshot of the Snyk App user interface and search for the recently added project](https://snyk.io/wp-content/uploads/blog-create-npm-packages-snyk-1240x310.png)

4. Confirm the repository has been successfully imported into Snyk.

![A screenshot of the project details shown in the Snyk App user interface](https://snyk.io/wp-content/uploads/blog-create-npm-packages-project-1240x305.png)

## Start creating modern npm packages

Let’s summarize everything you learned in this article. First, you became acquainted with setting up, creating and deploying a simple npm package. This was great to get familiar with what it takes to publish your own npm package for the first time. However, it’s quite manual and unsustainable to proceed in this way if you wish to make an npm package for production use. 

In order to accomplish making a production-ready package, you then learned how to build for both CommonJS (CJS) and ECMAScript (ESM) module formats, set up and write unit tests, implement security checks and automate version management and publishing. With this knowledge, you’re now ready to make many more npm packages of your own that’s easily consumable by the community or your company.

## Keep your npm packages secure

Secure your JS code and the packages you use with Snyk – for free.

[Sign up for free](https://app.snyk.io/login?cta=sign-up&loc=body&page=best-practices-for-creating-a-modern-npm-package)
<!-- /.block -->