Navigation

API Key Authentication

MongoDB Stitch provides the option for your application to authenticate using an API key.

Enable and Configure API Key Authentication

To configure API key authentication,

  1. Click Authentication. The page displays the available Authentication Providers.
  2. For API Keys, click the Edit button.
  3. In the Edit Auth Provider dialog,
    1. Set the API Keys switch to enabled.
    2. Enter a name for the API key in the Name text box.
    3. Click Save.
    4. Click Show Key..., and record the resulting alphanumeric string. This is the API key that you will provide to your application.

Incorporate into a Node.js Application

To incorporate API key authentication into a Node.js application:

  1. Include the MongoDB Stitch library in your project:

    npm install --save mongodb-stitch
    
  2. Instantiate a StitchClient object in your application:

    const stitch = require('mongodb-stitch');
    const stitchClient = new stitch.StitchClient('<your-app-id>');
    

    Replace <your-app-id> with your MongoDB Stitch App ID. To find your App ID, go to the Clients view in the MongoDB Stitch console. Click Copy App ID to copy your application ID.

  3. To authenticate using an API key, the StitchClient class provides the authenticate() function. Provide 'apiKey' as the first parameter to indicate that you are using API Key authentication, and the API key you created earlier as the second parameter.

    Warning

    Keep your API key a secret, and never place it in a publicly accessible location. For example, avoid storing your API key in source code repositories or revealing it on online code-sharing platforms such as Stack Overflow.

    stitchClient.authenticate('apiKey', '<your-api-key>').then(() => {
      console.log('Successfully authenticated as ' + StitchClient.authedId());
    }).catch((err) => {
      console.error('Error authenticating: ' + err);
    })