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

@authon/nextjs

v0.7.17

Published

Authon Next.js SDK — middleware, server helpers, and React components

Readme

English | 한국어

@authon/nextjs

Drop-in Next.js authentication with middleware, server helpers, and React components — Auth0 alternative

npm version License

Prerequisites

Before installing the SDK, create an Authon project and get your API keys:

  1. Create a project at Authon Dashboard

    • Click "Create Project" and enter your app name
    • Select the authentication methods you want (Email/Password, OAuth providers, etc.)
  2. Get your API keys from Project Settings → API Keys

    • Publishable Key (pk_live_...) — use in your frontend code
    • Test Key (pk_test_...) — for development, enables Dev Teleport
  3. Configure OAuth providers (optional) in Project Settings → OAuth

    • Add Google, Apple, GitHub, etc. with their respective Client ID and Secret
    • Set the redirect URL to https://api.authon.dev/v1/auth/oauth/redirect

Test vs Live keys: Use pk_test_... during development. Switch to pk_live_... before deploying to production. Test keys use a sandbox environment with no rate limits.

Install

npm install @authon/nextjs

Quick Start

// app/layout.tsx
import { AuthonProvider } from '@authon/nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <AuthonProvider
          publishableKey={process.env.NEXT_PUBLIC_AUTHON_PUBLISHABLE_KEY!}
        >
          {children}
        </AuthonProvider>
      </body>
    </html>
  );
}
// middleware.ts
import { authonMiddleware } from '@authon/nextjs';

export default authonMiddleware({
  publicRoutes: ['/', '/pricing', '/sign-in', '/sign-up'],
  signInUrl: '/sign-in',
});

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)'],
};
// app/page.tsx
'use client';
import { SignedIn, SignedOut, UserButton, useAuthon } from '@authon/nextjs';

export default function Home() {
  const { openSignIn } = useAuthon();
  return (
    <div>
      <SignedOut>
        <button onClick={() => openSignIn()}>Sign In</button>
      </SignedOut>
      <SignedIn>
        <UserButton />
      </SignedIn>
    </div>
  );
}

Common Tasks

Add Google OAuth Login

'use client';
import { useAuthon } from '@authon/nextjs';

export default function SignInPage() {
  const { client } = useAuthon();
  return (
    <button onClick={() => client?.signInWithOAuth('google')}>
      Sign in with Google
    </button>
  );
}

Protect a Route (Middleware)

// middleware.ts
import { authonMiddleware } from '@authon/nextjs';

export default authonMiddleware({
  publicRoutes: ['/', '/sign-in', '/sign-up', '/blog*'],
  signInUrl: '/sign-in',
});

Get Current User (Server Component)

// app/dashboard/page.tsx
import { currentUser } from '@authon/nextjs/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const user = await currentUser();
  if (!user) redirect('/sign-in');
  return <h1>Welcome, {user.displayName}</h1>;
}

Get Auth State (Route Handler)

// app/api/profile/route.ts
import { auth } from '@authon/nextjs/server';
import { NextResponse } from 'next/server';

export async function GET() {
  const { userId, user, getToken } = await auth();
  if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  return NextResponse.json({ user });
}

Add Email/Password Auth

'use client';
import { useAuthon } from '@authon/nextjs';
import { useState } from 'react';

export default function SignInPage() {
  const { client } = useAuthon();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <form onSubmit={async (e) => { e.preventDefault(); await client?.signInWithEmail(email, password); }}>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" />
      <button type="submit">Sign In</button>
    </form>
  );
}

Handle Sign Out

'use client';
import { useAuthon } from '@authon/nextjs';

export function SignOutButton() {
  const { signOut } = useAuthon();
  return <button onClick={() => signOut()}>Sign Out</button>;
}

Environment Variables

| Variable | Required | Description | |----------|----------|-------------| | NEXT_PUBLIC_AUTHON_PUBLISHABLE_KEY | Yes | Project publishable key (pk_live_... or pk_test_...) | | NEXT_PUBLIC_AUTHON_API_URL | No | Optional — defaults to api.authon.dev |

Security and verification

AuthonProvider keeps the browser session compatible with Next.js middleware by copying the access token to a JavaScript-readable cookie. The default cookie name is authon-token; set cookieName on both the provider and middleware when you need a different name. This compatibility cookie is intentionally not HttpOnly, so an XSS vulnerability can expose it. Use a strict Content Security Policy, avoid rendering untrusted HTML, and do not treat the cookie alone as server-side proof of identity.

Middleware checks JWT structure and the exp claim locally by default, rejecting malformed and expired tokens. This local check does not verify the JWT signature. Set verifyToken: true to opt in to authoritative remote verification against Authon; verification errors fail closed. API routes are public by default even when page routes are protected. Set protectApiRoutes: true (and normally verifyToken: true) to protect matching API routes.

currentUser() and auth() from @authon/nextjs/server remotely verify the token before returning identity data. They accept the current { valid, payload, user } response, legacy raw-user and { user } responses, and the API's wrapped { data: ... } response. Malformed or explicitly invalid responses return null/an unauthenticated state rather than trusting the cookie payload.

API Reference

Middleware

authonMiddleware({
  publicRoutes?: string[],
  signInUrl?: string,
  secretKey?: string,
  apiUrl?: string,
  timeoutMs?: number,
  cookieName?: string,
  verifyToken?: boolean,
  protectApiRoutes?: boolean,
})

Server Helpers (@authon/nextjs/server)

| Function | Returns | |----------|---------| | currentUser() | Promise<AuthonUser \| null> | | auth() | Promise<{ userId, user, getToken }> |

Client Components (re-exported from @authon/react)

AuthonProvider, useAuthon, useUser, SignIn, SignUp, UserButton, UserProfile, SignedIn, SignedOut, Protect, SocialButtons, useAuthonMfa, useAuthonPasskeys, useAuthonPasswordless, useAuthonWeb3, useAuthonSessions

Comparison

| Feature | Authon | Clerk | Auth.js | |---------|--------|-------|---------| | Pricing | Free | $25/mo+ | Free | | OAuth providers | 10+ | 20+ | 80+ | | Next.js middleware | Yes | Yes | Manual | | Server Components | Yes | Yes | Partial | | MFA/Passkeys | Yes | Yes | Plugin | | Web3 auth | Yes | No | No |

License

MIT