npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@auth0/auth0-hono

v1.2.6

Published

Auth0 Authentication middleware for Hono

Readme

Hono Auth0 Middleware

An Auth0 authentication middleware for Hono web framework. Built on top of the official Auth0 SDK, this package provides a simple way to secure your Hono applications using Auth0 authentication.

Installation

npm install @auth0/auth0-hono

Basic Usage

The simplest way to secure your Hono application is to implement the middleware at the application level. By default, all routes will require authentication.

import { Hono } from "hono";
import { auth } from "@auth0/auth0-hono";

const app = new Hono();

// Configure auth middleware with Auth0 options
app.use(
  auth({
    domain: process.env.AUTH0_DOMAIN,
    clientID: process.env.AUTH0_CLIENT_ID,
    clientSecret: process.env.AUTH0_CLIENT_SECRET,
    baseURL: process.env.BASE_URL,
    session: {
      secret: "password_at_least_32_characters_long",
    },
  }),
);

app.get("/", (c) => {
  return c.text(`Hello ${c.var.auth0Client?.getSession(c)?.user?.name}!`);
});

export default app;

Features

  • Auth0 Authentication Flow: Implements the Auth0 authorization code flow
  • Session Management: Built-in session support with configurable cookie settings
  • Configurable Routes: Customize login, callback, and logout route paths
  • Selective Protection: Choose which routes require authentication with the authRequired option
  • Token Management: Handles access tokens, ID tokens and refresh tokens
  • User Information: Automatically fetches and provides user profile data
  • Claim-Based Authorization: Middleware for authorizing based on claims from tokens
  • PKCE Support: Implements Proof Key for Code Exchange for enhanced security
  • Environment Flexibility: Works across various environments including Node.js, Bun, Cloudflare Workers, and more

Configuration Options

Required Configuration

| Option | Type | Description | | ---------- | -------- | -------------------------------------------------------- | | domain | string | Auth0 domain (e.g., your-tenant.auth0.com) | | baseURL | string | Base URL of your application (e.g., https://myapp.com) | | clientID | string | Client ID provided by Auth0 |

Optional Configuration

| Option | Type | Default | Description | | ----------------------------- | --------------- | ----------- | ----------------------------------------------------------------------------------------------------------- | | clientSecret | string | undefined | Client Secret provided by Auth0 (required for most flows) | | authRequired | boolean | true | Whether authentication is required for all routes | | idpLogout | boolean | false | Whether to perform logout at Auth0 when logging out locally | | pushedAuthorizationRequests | boolean | false | Enable Pushed Authorization Requests (PAR) | | customRoutes | Array<string> | [] | Specify which built-in routes to skip (options: 'login', 'callback', 'logout', 'backchannelLogout') | | errorOnRequiredAuth | boolean | false | Return 401 if the user is not authenticated | | attemptSilentLogin | boolean | false | Whether to attempt a silent login |

Routes Configuration

You can customize the paths for login, callback, logout, and backchannel logout endpoints:

app.use(
  auth({
    // ...required options
    routes: {
      login: "/custom-login",
      callback: "/auth-callback",
      logout: "/sign-out",
      backchannelLogout: "/backchannel-logout",
    },
  }),
);

Session Configuration

The middleware uses hono-sessions for session management. You can configure session options or disable sessions entirely:

app.use(
  auth({
    // ...required options
    session: {
      secret: "your-secure-encryption-key-minimum-32-chars",
      rolling: true, // optional, default: true
      absoluteDuration: 259200, // optional, default: 3 days (in seconds)
      inactivityDuration: 86400, // optional, default: 1 day (in seconds)
      cookie: {
        name: "my_session", // optional, default: "appSession"
        sameSite: "lax", // optional, default: "lax"
        secure: process.env.NODE_ENV === "production", // optional, auto-determined if not set
      },
    },
  }),
);

Authorization Parameters

You can customize the parameters sent to the authorization endpoint:

app.use(
  auth({
    // ...required options
    authorizationParams: {
      response_type: "code",
      scope: "openid profile email",
      response_mode: "query",
    },
  }),
);

Error handling

You can catch Auth0Exception errors and handle them in your application. This is useful for logging or displaying custom error messages.

import { Auth0Exception } from "@auth0/auth0-hono";

app.onError((err, c) => {
  // Handle Auth0-specific errors
  if (err instanceof Auth0Exception) {
    console.log(err);
    if (process.env.NODE_ENV === "development") {
      return err.getResponse();
    }
    return c.text(`Authentication Error`, 500);
  }
  // Handle other errors
  return c.text(`Internal Server Error: ${err.message}`, 500);
});

Configuration through Environment Variables

You can configure the middleware using environment variables instead of passing configuration options directly. This is particularly useful for deployment environments where you want to keep sensitive values in environment variables.

The following environment variables are supported:

| Environment Variable | Required | Description | | ------------------------------ | -------- | ------------------------------------------------------------------ | | AUTH0_DOMAIN | Yes | The Auth0 domain (e.g., your-tenant.auth0.com) | | AUTH0_CLIENT_ID | Yes | The client ID provided by Auth0 | | BASE_URL | Yes | The base URL of your application (e.g., https://myapp.com) | | AUTH0_CLIENT_SECRET | No | The client secret provided by Auth0 (required for most flows) | | AUTH0_AUDIENCE | No | The API audience identifier for your Auth0 API | | AUTH0_SESSION_ENCRYPTION_KEY | No | The secret key used for session encryption (minimum 32 characters) |

When environment variables are set, they will be used as defaults for the corresponding configuration options. You can still override them by passing explicit values in the configuration object.

Example using only environment variables:

# .env file
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your_client_id
AUTH0_CLIENT_SECRET=your_client_secret
BASE_URL=https://localhost:3000
AUTH0_SESSION_ENCRYPTION_KEY=your_32_character_minimum_secret_key
AUTH0_AUDIENCE=https://api.yourapp.com
import { Hono } from "hono";
import { auth } from "@auth0/auth0-hono";

const app = new Hono();

// No configuration object needed - will use environment variables
app.use(auth());

app.get("/", (c) => {
  return c.text(`Hello ${c.var.auth0Client?.getSession(c)?.user?.name}!`);
});

Example with mixed configuration (environment + explicit):

app.use(
  auth({
    // These will override environment variables if set
    authRequired: false,
    routes: {
      login: "/custom-login",
      callback: "/auth-callback",
    },
    // Other options like domain, clientID, etc. will use environment variables
  }),
);

Advanced Usage

Selective Route Protection

Only protect specific routes:

import { Hono } from "hono";
import { auth, requiresAuth } from "@auth0/auth0-hono";

const app = new Hono();

app.use(
  auth({
    // ...required options
    authRequired: false,
  }),
);

// Public route - no authentication required
app.get("/", (c) => {
  return c.text("This is a public page");
});

// Protected route - authentication required
app.use("/profile/*", requiresAuth());
app.get("/profile", (c) => {
  const user = c.var.oidc.user;
  return c.text(`Hello ${user.name || user.sub}!`);
});

Silent Login Attempt

Try to authenticate silently without user interaction:

import { Hono } from "hono";
import { auth, attemptSilentLogin } from "@auth0/auth0-hono";

const app = new Hono();

app.use(
  auth({
    /* ...options */
    authRequired: false,
  }),
);

app.get("/", attemptSilentLogin(), async (c) => {
  if (c.var.oidc?.isAuthenticated) {
    return c.text(`Hello ${c.var.oidc.user.name}!`);
  }

  return c.text("You are not logged in");
});

Advanced Login Options

The login middleware supports several advanced options:

import { login } from "@auth0/auth0-hono";

// Custom login options
app.get("/custom-login", async (c) => {
  return login({
    // Redirect user to this URL after successful authentication
    redirectAfterLogin: "/dashboard",

    // Additional authorization parameters to send to the identity provider
    authorizationParams: {
      prompt: "consent",
      acr_values: "level2",
      login_hint: "[email protected]",
    },

    // Forward specific query parameters from the login request to the authorization request
    forwardQueryParams: ["ui_locales", "login_hint", "campaign"],

    // Attempt silent authentication (no user interaction)
    silent: false,
  })(c);
});

With forwardQueryParams, you can pass query parameters from the login request to the authorization request. This is useful for:

  • Passing UI locale preferences (ui_locales)
  • Forwarding login hints to the identity provider
  • Maintaining tracking parameters throughout the authentication flow
  • Supporting custom parameters your identity provider accepts

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.