> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nmbr.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Getting Started

> The fastest way to ship a fully-featured payroll system in your app.

The Nmbr Component offers a fully-featured payroll suite in a lightweight integration. It takes less than an hour for a single developer to add payroll features to any app using our embeddable payroll module, designed and built by our in-house experts to work seamlessly with your data in any environment.

To get started, you will need the following:

* A Partner ID, API Key, and API Secret from our [Portal](/portal/working-with-the-nmbr-dashboard).
* The ability to add a server-side endpoint in your app's API
* The ability to add or change HTML pages in your app's UI

## How it works

You will be adding a javascript `<script>` tag to your existing web application in order to load and display the Nmbr Component. The component is loaded in an iframe and sized to fit its container. You will need to ensure access to the page containing the component is sufficiently protected via authentication and authorization, as the Nmbr Component has no access to your front-end user information.

## Security

Interacting with the Nmbr Component along with any API calls required to load or change data requires a signature created by your web server. Before making an API request, the component will use your `signing endpoint` to retrieve a signature to be sent with the API request. The Nmbr API automatically validates this signature to ensure secure communication between the Nmbr Component and the Nmbr API.

## 1 - Set up the Signing Endpoint

### Install a JWT library

Nmbr Components use JSON Web Tokens (JWTs) signed on your server to prove a user is authorized to read and write payroll data. Their website features [libraries in several languages](https://jwt.io/libraries), although some listed may be out of date.

<CodeGroup>
  ```bash Ruby theme={null}
  gem install jwt
  ```

  ```bash Node theme={null}
  npm install jsonwebtoken
  ```

  ```bash PHP theme={null}
  composer require firebase/php-jwt
  ```

  ```bash .NET theme={null}
  dotnet add package System.IdentityModel.Tokens.Jwt
  ```
</CodeGroup>

> 🙋 Don't want to use a library?
> You may also implement signing yourself by following the JWT spec ([RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519)).

### Create a signing endpoint

Add an endpoint on your server to sign pre-formed JWTs. When you mount Nmbr Components in your app (step 2), this endpoint will be used to initialize the library.

<CodeGroup>
  ```ruby Ruby theme={null}
  # app.rb
  require 'jwt'
  require 'sinatra'

  NMBR_API_SECRET = ENV['NMBR_API_SECRET'] || 'invalid-secret'

  # Sign request bodies with the SHA-256 hash of your API Secret,
  # formatted as a hex string (though base64 is supported too)
  SIGNING_HASH = Digest::SHA256.hexdigest(NMBR_API_SECRET)

  post '/sign_nmbr_request' do
    # Your app should authenticate the user and
    # ensure they are authorized to administer payroll
    payload = JSON.parse(request.body.read)
    token = JWT.encode(payload, SIGNING_HASH, 'HS256')
    status 201
    body token
  end

  # Start the server
  set :port, ENV['PORT'] || 8080
  run Sinatra::Application
  ```

  ```typescript Node theme={null}
  // server.js
  import jwt from 'jsonwebtoken';
  import express from 'express';
  import crypto from 'node:crypto';

  const PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080;
  const NMBR_API_SECRET = process.env.NMBR_API_SECRET ?? 'invalid-secret';

  const SIGNING_HASH = crypto // Sign request bodies
    .createHash('sha256') // with the SHA-256 hash
    .update(NMBR_API_SECRET) // of your API Secret
    .digest('hex'); // formatted as a hex string
  // (though base64 is supported too)
  const app = express();

  app.post(
    '/sign_nmbr_request',
    // Your app should authenticate the user and
    // ensure they are authorized to administer payroll
    express.json(),
    (req, res) => res.status(201).send(jwt.sign(req.body, SIGNING_HASH)),
  );

  app.listen(PORT, () => console.log(`Running on port ${PORT}`));
  ```

  ```php PHP theme={null}
  <?php
  # index.php
  require_once 'vendor/autoload.php';
  use Firebase\JWT\JWT;
  use Firebase\JWT\Key;

  $NMBR_API_SECRET = getenv('NMBR_API_SECRET') ?: 'invalid-secret';

  # Sign request bodies with the SHA-256 hash of your API Secret,
  # formatted as a hex string (though base64 is supported too)
  $SIGNING_HASH = hash('sha256', $NMBR_API_SECRET);

  # Create a simple router for demonstration purposes
  $requestMethod = $_SERVER['REQUEST_METHOD'];
  $requestUri = $_SERVER['REQUEST_URI'];

  if ($requestMethod === 'POST' && $requestUri === '/sign_nmbr_request') {
      # Your app should authenticate the user and
      # ensure they are authorized to administer payroll
      $payload = json_decode(file_get_contents('php://input'), true);
      $token = JWT::encode($payload, $SIGNING_HASH, 'HS256');
      http_response_code(201);
      echo $token;
  } else {
      http_response_code(404);
      echo 'Not Found';
  }
  ```

  ```cs .NET theme={null}
  // YourController.cs
  // Install-Package System.IdentityModel.Tokens.Jwt
  // Install-Package Microsoft.AspNetCore.WebUtilities
  // Install-Package Newtonsoft.Json
  using System;
  using System.Text;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.IdentityModel.Tokens;
  using System.IdentityModel.Tokens.Jwt;
  using Microsoft.AspNetCore.WebUtilities;
  using Newtonsoft.Json.Linq;

  namespace YourNamespace
  {
      public class YourController : ControllerBase
      {
          private readonly string _nmbrApiSecret = Environment.GetEnvironmentVariable("NMBR_API_SECRET") ?? "invalid-secret";

          // Sign request bodies with the SHA-256 hash of your API Secret,
          // formatted as a hex string (though base64 is supported too)
          private string SigningHash => WebEncoders.Base64UrlEncode(
              System.Security.Cryptography.SHA256.HashData(
                  Encoding.UTF8.GetBytes(_nmbrApiSecret)
              )
          );

          [HttpPost]
          [Route("sign_nmbr_request")]
          public IActionResult SignNmbrRequest([FromBody] JObject payload)
          {
              // Your app should authenticate the user and
              // ensure they are authorized to administer payroll

              // Convert the JObject payload to a dictionary
              var payloadDictionary = payload.ToObject<Dictionary<string, object>>();

              // Create a security key using the API secret
              var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_nmbrApiSecret));

              // Create signing credentials
              var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

              // Create a JWT header with the signing credentials
              var header = new JwtHeader(signingCredentials);

              // Create a JWT payload from the payload dictionary
              var jwtPayload = new JwtPayload(payloadDictionary);

              // Create the JWT token
              var token = new JwtSecurityToken(header, jwtPayload);

              // Write the token to a string
              var tokenHandler = new JwtSecurityTokenHandler();
              var signedToken = tokenHandler.WriteToken(token);

              // Return the signed token as plain text
              return Content(signedToken, "text/plain");
          }
      }
  }
  ```
</CodeGroup>

## 2 - Mount the Run Screen

The Nmbr Component uses a single script to securely initialize, load, and orchestrate UI from Nmbr's servers inside your app.

### Install `host.js`

Download the script directly from Nmbr's CDN

```html payroll.html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <title>Nmbr Components Demo</title>
    <script type="importmap">
    {
      "imports": {
        "@nmbrco/components": "https://static.sandbox.nmbr.co/components/*/host.js"
      }
    }
    </script>

    <!-- Meta tags; style links; other scripts; etc -->
  </head>

  <body>
    <!-- Continued below>
  </body>
</html>
```

If you're using Vite, the importmap below won't work. See [Using Vite](#using-vite) for the alternative.

### Initialize Nmbr Components

As soon as your page allows it, initialize `host.js` to start loading resources that will make the components load faster and smoother for your users.

```html payroll.html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <!-- Critical scripts; the importmap from above; etc -->

    <script type="module">
      import nmbr from '@nmbrco/components';

      // You must provide these when initializing the host script.
      // These are anonymized identifiers we generate that do not contain PII.
      const partnerId = 'your-partner-id';
      const companyId = 'user-company-id';

      // Initialize Nmbr Components as early as you can
      // to minimize perceived latency for the user.
      window.components = nmbr.initialize({
        companyId,
        partnerId,
        sandbox: true,
        signingUrl: '/sign_nmbr_request', // Use the same value as above
        // [optional params]
        // sandbox: false,
        // sign: async (json: string): Promise<string> => {
        //   const response = await fetch(this.signingUrl, {
        //     method: 'POST',
        //     headers: {
        //       Accept: 'text/plain',
        //       'Content-Type': 'application/json',
        //     },
        //     body: json,
        //   });
        //
        //   return response.text();
        // },
      });
    </script>

    <!-- Meta tags; style links; other scripts; etc -->
  </head>

  <body>
    <!-- Continued below -->
  </body>
</html>
```

#### Types

The type information for the configuration object passed to `nmbr.initialize` is as follows:

```ts theme={null}
type InitializationConfig = {
  signingUrl?: string | never; // A `signingUrl` must be provided if the `sign` function is not provided
  sign?: (message: string) => Promise<string> | never; // A `sign` function must be provided if the `signingUrl` is not provided
  companyId: string; // The company ID to load the component for
  partnerId: string; // Your partner ID
  sandbox?: boolean;
  theme?: CustomTheme; //  See Theming > Type Information
  settings?: Settings; // See Customization > Settings > Available Settings
};
```

For more information on the `theme` types, see the [Theming page](/components/theming#type-information)

For more information on the `settings` types, see the [Customization page](/components/customization#available-settings)

### Using Vite

If you're using Vite, the importmap pattern won't work. In dev mode, Vite tries to resolve package-name imports like `@nmbrco/components` from your local `node_modules` folder before the browser sees the importmap. Since `@nmbrco/components` is loaded from Nmbr's CDN rather than installed as an npm package, Vite returns a 404.

If you're using Vite, use this dynamic import instead of the importmap install and static import shown above. The full URL points directly at Nmbr's CDN, so Vite doesn't try the node\_modules lookup:

```html payroll.html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <!-- Critical scripts; etc. No importmap needed. -->

    <script type="module">
      // @nmbrco/components is a CDN script, not an npm package.
      // Use a dynamic import with the full URL so Vite skips the node_modules lookup.
      const nmbr = (await import('https://static.sandbox.nmbr.co/components/*/host.js')).default;

      const partnerId = 'your-partner-id';
      const companyId = 'user-company-id';

      window.components = nmbr.initialize({
        companyId,
        partnerId,
        sandbox: true,
        signingUrl: '/sign_nmbr_request',
      });
    </script>

    <!-- Meta tags; style links; other scripts; etc -->
  </head>

  <body>
    <!-- Continued below -->
  </body>
</html>
```

### Load the Run Payroll component

Once your `host.js` script is initialized, you may embed Nmbr's Run Payroll component into any element on your page.

```html payroll.html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <!-- From above -->
  </head>

  <body>
    <header>
      <!-- Your app's topbar content -->
    </header>

    <div>
      <aside>
        <!-- Your app's sidebar content -->
      </aside>

      <main id="nmbr-container">
        <!-- Your app might do more; we will embed directly here -->
      </main>
      <script type="text/javascript">
        // Start loading the component as soon as its container is in the DOM
        const container = document.querySelector('#nmbr-container');
        const frame = components.load('run', container, {
          // hideUntilReady = false
        });

        frame.ready
          .then(() => console.log('Nmbr Components Run Screen loaded'))
          .catch((err) =>
            console.error('Could not load Nmbr Components Run Screen', err),
          );
      </script>
    </div>
  </body>
</html>
```

## 3 - Test your page

At this point, you have finished writing all code required to set up Nmbr Components. Let's see it in action!

### Load the payroll page

Start by loading the page you set up in Step 2; you should see the embedded iframe start loading in your container. New companies will always start at the Company Setup screen; once they have completed setup the component will default to the Payroll Dashboard.

### Run a payroll in sandbox

Once you've confirmed the component is loading, it is time to submit data. To simulate payroll before you go live, import the sandbox version of the scripts and provide the additional option `sandbox: true` for Nmbr Components. (You may also need to provide different partner credentials configured for the sandbox environment).

```html theme={null}
<script type="importmap">
  {
    "imports": {
      "@nmbrco/components": "https://static.sandbox.nmbr.co/components/*/host.js"
    }
  }
</script>
```

```typescript theme={null}
const components = nmbr.initialize({
  // ...
  sandbox: true,
});
```

## Congratulations!

You have successfully embedded Nmbr Components in your app. Consider next how else to customize your integration:

* Mirror business, employee, and other data to Nmbr to pre-fill payroll fields
