Relay API Authentication

Community maintained

To restrict access to the resources served by your API, a check needs to be made to determine whether the incoming request contains valid authorization information. There are various methods for including authorization information in a request, but for integration with Auth0, your API needs to check for a valid JSON Web Token (JWT). When users log into your application, they will receive an id_token and an access_token which are both JWTs. The specific JWT that needs to be sent to your API is the access_token.

Add the Dependencies

Add express-jwt and express-graphql as dependencies.

npm install express-jwt express-graphql --save


By default, your API will be set up to use RS256 as the algorithm for signing tokens. Since RS256 works by using a private/public keypair, tokens can be verified against the public key for your Auth0 account. This public key is accessible at https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json.

Configure the express-jwt middleware to use the remote JWKS for your Auth0 account.

// server.js

const express = require('express');
const app = express();
const graphqlHttp   = require('express-graphql');
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');

// Authentication middleware. When used, the
// access token must exist and be verified against
// the Auth0 JSON Web Key Set
const authenticate = jwt({
  // Dynamically provide a signing key
  // based on the kid in the header and 
  // the singing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`

  // Validate the audience and the issuer.
  audience: '{YOUR_API_IDENTIFIER}',
  issuer: `https://YOUR_AUTH0_DOMAIN/`,
  algorithms: ['RS256']

Secure your API

In your Relay app, you serve a GraphQL object from a single endpoint, which is typically at /graphql. You can protect this endpoint globally with the express-jwt middleware.

app.use('/graphql', authenticate, graphqlHttp({schema: schema}));

Send an Access Token from your Front End

When you send a request to the GraphQL endpoint, you need to include the user's access_token as an Authorization header. This can be done by tapping into Relay's network layer and extending requests to include a header.

const token = localStorage.getItem('access_token');

  new Relay.DefaultNetworkLayer('http://localhost:3000/graphql', {
    headers: {
      Authorization: 'Bearer ' + token
Previous Tutorial
1. Getting Started
Use Auth0 for FREECreate free Account