Add the Hanko API URL

Retrieve the API URL from the Hanko console and place it in your .env file.

.env
HANKO_API_URL=https://f4****-4802-49ad-8e0b-3d3****ab32.hanko.io
If you are self-hosting Hanko you need to provide your own URL.

Hanko Authentication with JWT

Upon a successful login, Hanko sends a cookie containing a JSON Web Token (JWT). You can use this JWT to authenticate requests on your backend.

Steps to Authenticate Requests

  1. Retrieve the JSON Web Key Set (JWKS): The JWKS has the public keys to verify the JWT. Fetch it from the Hanko API’s .well-known/jwks.json endpoint.

  2. Verify the JWT: Use the JWKS to verify the JWT.

Node-based Backend Example

In the following example, we demonstrate how to implement a custom middleware in an Express.js backend using express-jwt and jwks-rsa packages.

const express = require("express");
const cookieParser = require("cookie-parser");
const jose = require("jose");
const dotenv = require("dotenv").config();

const app = new Express();
app.use(cookieParser());

const JWKS = jose.createRemoteJWKSet(
  new URL(`${process.env.HANKO_API_URL}/.well-known/jwks.json`)
);

async function validateToken(req, res, next) {
  let token = null;
  if (
    req.headers.authorization &&
    req.headers.authorization.split(" ")[0] === "Bearer"
  ) {
    token = req.headers.authorization.split(" ")[1];
  } else if (req.cookies && req.cookies.hanko) {
    token = req.cookies.hanko;
  }
  if (token === null || token.length === 0) {
    res.status(401).send("Unauthorized");
    return;
  }
  let authError = false;
  await jose.jwtVerify(token, JWKS).catch((err) => {
    authError = true;
    console.log(err);
  });
  if (authError) {
    res.status(401).send("Authentication Token not valid");
    return;
  }
  next();
}

app.use(validateToken);

app.get("/protected", function (req, res) {
  res.sendStatus(200);
});

Try it yourself

Node and Express.js example (React frontend)

Full source code available on our GitHub.

Node and Express.js example (Vue frontend)

Full source code available on our GitHub.

Node and Express.js example (Svelte frontend)

Full source code available on our GitHub.