---
title: "Add JWT Authentication to Your Total.js API"
description: "Secure your Total.js API using JWT authentication with JWKS."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/javascript/totaljs/jwt-backend"
framework: "Total.js"
language: "JavaScript"
authStrategy: "JWT with JWKS"
pageType: use-case
---

# Add JWT Authentication to Your Total.js API

Secure your Total.js API using JWT authentication with JWKS.

## How Zuplo Handles It

Let Zuplo issue short-lived JWTs signed with a JWKS your Total.js backend can verify — no long-lived API keys touch your origin.

## Total.js Backend Code

```javascript
const jwt = require("jsonwebtoken");
const jwksClient = require("jwks-rsa");

const ISSUER = "https://my-api-a32f34.zuplo.api/__zuplo/issuer";

const client = jwksClient({
  jwksUri: `${ISSUER}/.well-known/jwks.json`,
  cache: true,
  cacheMaxAge: 600000,
});

function getKey(header, callback) {
  client.getSigningKey(header.kid, (err, key) => {
    if (err) return callback(err);
    callback(null, key.getPublicKey());
  });
}

// Middleware for JWT authentication
F.middleware("jwt", function ($, next) {
  const auth = $.headers["authorization"];

  if (!auth || !auth.startsWith("Bearer ")) {
    $.res.status(401);
    $.json({ error: "No token provided" });
    return;
  }

  const token = auth.slice(7);

  jwt.verify(
    token,
    getKey,
    { issuer: ISSUER, algorithms: ["RS256"] },
    (err, decoded) => {
      if (err) {
        $.res.status(401);
        $.json({ error: "Invalid token", details: err.message });
        return;
      }
      $.user = decoded;
      next();
    },
  );
});

// Route definition
exports.install = function () {
  ROUTE("GET /protected", protected_action, ["jwt"]);
};

function protected_action($) {
  $.json({ message: "Access granted", user: $.user });
}
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
