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

@wilsoon/auth-next

v2.3.0

Published

OpenID Connect for the Next.js App Router: verified sessions, middleware and hardened cookie storage

Readme

@wilsoon/auth-next

OpenID Connect for the Next.js App Router: verified sessions in Server Components and Route Handlers, plus route-protecting Edge Middleware that refreshes expiring tokens.

Part of the Wilsoon Node OIDC Kit - an OpenID Connect relying party for TypeScript. Siblings: @wilsoon/auth-core · @wilsoon/auth-react · @wilsoon/auth-next.

Features

  • Verified sessions: getSession() verifies the ID token's signature, issuer, audience and expiry against the provider's JWKS on every request, so user.role and user.authMethods can gate access.
  • Edge Middleware: Protect your routes, enforce role/amr policies, and refresh tokens at the Edge.
  • Server Components: Access session data securely using next/headers without client-side waterfalls.
  • Client Components: Re-exports @wilsoon/auth-react so you can use it client-side with "use client".

Installation

npm install @wilsoon/auth-next @wilsoon/auth-core @wilsoon/auth-react

Full end-to-end recipes, migration notes and a troubleshooting table live in the integration guide.

Basic Usage

Keep one config object and share it across middleware, server helpers and the provider.

// lib/auth-config.ts
import type { AuthConfig } from "@wilsoon/auth-core";

export const authConfig: AuthConfig = {
  clientId: process.env.OIDC_CLIENT_ID!,
  issuer: "https://id.example.com",
  redirectUri: "https://app.example.com/callback",
};

1. Protecting Routes with Middleware

Create a middleware.ts file in the root or src/ directory of your Next.js project.

import { createAuthMiddleware } from "@wilsoon/auth-next";
import { authConfig } from "./lib/auth-config";

export const middleware = createAuthMiddleware({
  ...authConfig,
  loginPath: "/auth",
  // Verifies the ID token per request (default). Optional policy:
  roles: ["admin"],
  unauthorizedPath: "/unauthorized",
});

// Protect specific routes
export const config = {
  matcher: ["/dashboard/:path*", "/profile/:path*"],
};

The middleware verifies the session, refreshes an access token that is near expiry (writing the rotated tokens back to the cookie), and clears the cookie instead of looping when a session cannot be verified. Pass verify: false to get 1.x behaviour - presence-of-cookie routing only, which any client can fake.

A refresh token is single-use where the provider rotates it, so a page load that sends ten requests through the middleware with one cookie must not send ten refreshes: nine of them present a token that has just been rotated away, and a provider that reads that as theft revokes the session. Refreshes therefore start refreshThresholdSeconds before expiry (default 300) and only on navigations, which is one request per page load. Set refreshOn: "request" to refresh from any request instead. A token with nothing left refreshes whatever the setting, so an app that only ever sends fetches still renews, and a refresh that fails while the access token is still valid leaves the session alone for a later request to retry.

2. Accessing Session in Server Components

import { getSession } from "@wilsoon/auth-next";
import { authConfig } from "@/lib/auth-config";

export default async function DashboardPage() {
  const { user } = await getSession(authConfig);

  if (!user) return <div>Access Denied</div>;

  return (
    <div>
      <h1>Welcome to your Dashboard, {user.email}!</h1>
      <p>Role: {user.role}</p>
    </div>
  );
}

user is null unless the ID token verified, so user.role is a verified claim rather than a decoded one. When a cookie was present but unusable, the reason is in error.

For a guard clause, requireSession() throws instead:

import { requireSession } from "@wilsoon/auth-next";
import { AMR } from "@wilsoon/auth-core";

const user = await requireSession(authConfig, { roles: ["admin"], amr: [AMR.FIDO] });

Verifying clients are cached per configuration, so the provider's JWKS is fetched once per runtime instance rather than once per render.

3. Handling the callback in a Route Handler

import { cookies } from "next/headers";
import { AuthClient } from "@wilsoon/auth-core";
import { ServerCookieStorage } from "@wilsoon/auth-next";
import { authConfig } from "@/lib/auth-config";

export async function GET(request: Request) {
  const client = new AuthClient(authConfig, new ServerCookieStorage(await cookies(), { domain: ".example.com" }));

  // Validates state, exchanges the code with its PKCE verifier, verifies the ID token.
  const { user } = await client.handleCallback(request.url, { persistTokens: true });

  return Response.redirect(new URL(`/dashboard?welcome=${encodeURIComponent(user?.name ?? "")}`, request.url));
}

Start the flow from a matching route with client.createAuthorizeUrl(), which persists state, nonce and the PKCE verifier into HttpOnly cookies through the same storage - the two halves are no longer the caller's problem.

4. Client-Side Usage

@wilsoon/auth-next seamlessly re-exports @wilsoon/auth-react. You can import the AuthProvider and useAuth hook directly from @wilsoon/auth-next for your Client Components.

"use client";

import { useAuth, AuthProvider } from "@wilsoon/auth-next";

// ...

Client state is for rendering only - the server helpers above are what gate access.

Environment

Designed specifically for Next.js 13+. ServerCookieStorage reads cookies anywhere cookies() works and writes them in Route Handlers, Server Actions and middleware; in a Server Component, where Next.js forbids writes, it throws StorageUnavailableError explaining where to move the call.

License

MIT - free use, forking and redistribution, with no warranty of any kind.