Node.js - api()

Creates a new HTTP API.

import { api } from '@nitric/sdk'

const publicApi = api('public')

Parameters

  • Name
    name
    Required
    Required
    Type
    string
    Description

    The unique name of this API within the app. Subsequent calls to api with the same name will return the same object.

  • Name
    options
    Optional
    Optional
    Type
    object
    Description

    Additional options when creating the API.

    • Name
      path
      Optional
      Optional
      Type
      string
      Description

      Base path for all routes in the API.

    • Name
      middleware
      Optional
      Optional
      Type
      HttpMiddleware or HttpMiddleware[]
      Description

      Middleware to apply to all routes and methods of the API.

    • Name
      security
      Optional
      Optional
      Type
      OidcOptions[]
      Description

      Security rules to apply with scopes to the entire API.

OidcOptions Parameters

  • Name
    name
    Required
    Required
    Type
    string
    Description

    the name of the security definition

  • Name
    issuer
    Required
    Required
    Type
    string
    Description

    the issuer for the JWT tokens e.g. https://account.region.auth0.com

  • Name
    audiences
    Required
    Required
    Type
    string[]
    Description

    the aud that will be applied to JWT tokens from the issuer.

  • Name
    scopes
    Required
    Required
    Type
    string[]
    Description

    the scopes that will be required to authenticate.

Notes

The middleware property on the options param is useful for applying universal middleware such as CORS headers or Auth, across an entire API from a single place.

Examples

Create an API

import { api } from '@nitric/sdk'

const publicApi = api('public')

Create an API with universal middleware

import { api } from '@nitric/sdk'
import { authMiddleware } from '../middleware'

const privateApi = api('private', { middleware: authMiddleware })

Define middleware

const authMiddleware = async (ctx, next) => {
  // Perform auth validation.
  return await next(ctx)
}

Notes

Middleware services are supplied an HttpContext object and a next() function which calls the next middleware in the chain.

Create an API with a base path

If you need to put all the routes in your api below a shared base path, you can do that with the path option. In this example we ensure all routes start with /api/v1/ before the route specific path.

import { api } from '@nitric/sdk'

const apiV1 = api('private', { path: '/api/v1' })

Apply JWT authentication to an API

import { api, oidcRule } from '@nitric/sdk'

const defaultSecurityRule = oidcRule({
  name: 'default',
  audiences: ['https://test-security-definition/'],
  issuer: 'https://dev-abc123.us.auth0.com',
})

const secureApi = api('main', {
  // apply the security definition to all routes in this API.
  security: [defaultSecurityRule()],
})