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

@next-safe-action/adapter-better-auth

v0.1.6

Published

Better Auth adapter for next-safe-action.

Downloads

1,820

Readme

This adapter offers a way to seamlessly integrate next-safe-action with Better Auth. It provides a betterAuth() function that fetches the session, blocks unauthenticated requests, and injects fully-typed { user, session } data into the action context.

Requirements

  • Next.js >= 15.1.0
  • next-safe-action >= 8.4.0
  • better-auth >= 1.5.0

Installation

npm i next-safe-action better-auth @next-safe-action/adapter-better-auth

Quick start

1. Set up Better Auth

Create your Better Auth server instance:

// src/lib/auth.ts
import { betterAuth } from "better-auth";

export const auth = betterAuth({
	// ...your config (database, plugins, etc.)
});

2. Create an authenticated action client

// src/lib/safe-action.ts
import { createSafeActionClient } from "next-safe-action";
import { betterAuth } from "@next-safe-action/adapter-better-auth";
import { auth } from "./auth";

export const actionClient = createSafeActionClient();

export const authClient = actionClient.use(betterAuth(auth));

3. Use it in your actions

// src/app/actions.ts
"use server";

import { z } from "zod";
import { authClient } from "@/lib/safe-action";

export const updateProfile = authClient
	.inputSchema(z.object({ name: z.string().min(1) }))
	.action(async ({ parsedInput, ctx }) => {
		// ctx.auth.user and ctx.auth.session are fully typed
		const userId = ctx.auth.user.id;

		await db.user.update({
			where: { id: userId },
			data: { name: parsedInput.name },
		});

		return { success: true };
	});

How it works

betterAuth() creates a pre-validation middleware for the safe action client's .use() chain:

  1. Fetches the session by calling auth.api.getSession({ headers: await headers() })
  2. Blocks unauthenticated requests by calling unauthorized() from next/navigation when no session exists
  3. Injects typed context by passing { auth: { user, session } } to next(), merging it into the action context

unauthorized() and auth interrupts

The default behavior uses unauthorized() from next/navigation, which requires experimental.authInterrupts in your Next.js configuration:

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
	experimental: {
		authInterrupts: true,
	},
};

export default nextConfig;

Custom authorization

Pass an authorize callback to customize the authorization flow. The session is pre-fetched and passed to the callback:

import { unauthorized } from "next/navigation";
import { betterAuth } from "@next-safe-action/adapter-better-auth";
import { auth } from "./auth";

// Role-based access
export const adminClient = actionClient.use(
	betterAuth(auth, {
		authorize: ({ authData, next }) => {
			if (!authData || authData.user.role !== "admin") {
				unauthorized();
			}
			return next({ ctx: { auth: authData } });
		},
	})
);

authorize callback parameters

  • authData: the pre-fetched session data ({ user, session } | null)
  • ctx: the current action context from preceding middleware
  • next: call this to continue the middleware chain, pass { ctx } to inject context

Server Action cookies

If your actions call Better Auth functions that set cookies (e.g. signInEmail, signUpEmail), add the nextCookies() plugin to your Better Auth instance. Refer to the Better Auth documentation for more details.

// src/lib/auth.ts
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";

export const auth = betterAuth({
	// ...your config
	plugins: [
		// ...other plugins
		nextCookies(), // must be the last plugin in the array
	],
});

API reference

betterAuth(auth, opts?)

Creates a middleware function for use with the safe action client's .use() method.

Parameters:

  • auth: the Better Auth server instance (return value of betterAuth())
  • opts?: optional object with an authorize callback for custom authorization logic

Returns: a middleware function compatible with .use()

Exported types

  • BetterAuthContext<Options>: the context shape added by the middleware ({ auth: { user, session } })
  • AuthorizeFn<Options, NextCtx>: the authorize callback signature
  • BetterAuthOpts<Options, NextCtx>: the options object type for betterAuth

Documentation

For full documentation, visit next-safe-action.dev/docs/integrations/better-auth.

Preview releases powered by pkg.pr.new

pkg.pr.new

License

MIT