NuID Node.js SDK


The Node.js SDK provides an interface for interacting with NuID APIs and utilities. We encourage you to contact us if you have any questions. We also encourage you to open an issue or pull request if you have any issues or suggestions.

Installation


Install the package from our GitHub source. Be sure to add your API Key to your environment configuration.

$ cd my-app/server
$ npm install -s @nuid/sdk-nodejs
# or
$ yarn add @nuid/sdk-nodejs

# Add the API key to your environment configuration
$ export NUID_API_KEY="<API KEY>"

Usage


To use the package, import it into your server and configure it:

// my-app/server/src/app.js

const express = require('express')
const fetch = require('node-fetch')
const nuidApi = require('@nuid/sdk-nodejs').default({
  auth: { apiKey: process.env.NUID_API_KEY } // '<API KEY>'
})

const server = express()
server.listen(process.env.PORT)

// see endpoint examples below

Once you have a configured sdk client, you can use it to dispatch requests to the API. Requests that succeed (return a 200 or 201) will be returned normally. All other requests will be thrown/rejected. The body of each response will be parsed and placed in the parsedBody attribute on the response for you.

// my-app/server/src/app.js

// ... server setup code ...

// Registration route handler
server.post('/register', async (req, res) => {
  try {
    const email = req.body.email
    const createRes = await nuidApi.auth.credentialCreate(req.body.credential)
    const nuid = createRes.parsedBody['nu/id']
    const user = await db.save('user', { email, nuid })
    res.status(204).send({ user })
  } catch (res) {
    res.sendStatus(400)
  }
})

// Challenge route handler
server.post('/challenge', async (req, res) => {
  const email = req.body.email
  const user = await db.find('user', {email: email}).first
  if (!user) {
    res.sendStatus(401)
    return 
  }

  try {
    const credentialRes = await nuidApi.auth.credentialGet(user.nuid)
    const credential = credentialRes.parsedBody['nuid/credential']
    const challengeRes = await nuidApi.auth.challengeGet(credential)
    const challengeJwt = challengeRes.parsedBody['nuid.credential.challenge/jwt']
    res.send({challengeJwt: challengeJwt})
  } catch (res) {
    res.sendStatus(401)
  }
})

// Login route handler
server.post('/login', async (req, res) => {
  const user = await db.find('user', { email: req.body.email }).first
  if (!user) {
    res.sendStatus(401)
    return 
  }

  try {
    const { challengeJwt, proof } = req.body
    await nuidApi.auth.challengeVerify(challengeJwt, proof)
    res.status(201).json({ user })
  } catch (res) {
    res.sendStatus(401)
  }
})

You can see a complete code example using the Node.js SDK package in our examples repo, or go read our Integrating with NuID guide.