@authaction/server-sdk

AuthAction server-side SDK — session-based auth for Next.js, Nuxt, Remix, and SvelteKit
734
Install
npm install @authaction/server-sdk
Latest Version:0.2.0
Vue:3
License:MIT
Last Updated:Sep 20, 2026
Links: npm
Maintainer: authaction-dev

@authaction/server-sdk

Server-side session auth for Next.js, Nuxt, Remix, and SvelteKit. Handles the full OAuth2 PKCE flow server-side — exchanges the authorization code, encrypts tokens in an HTTP-only cookie session, and provides helpers for reading the session in server components and route handlers.

For browser-side (SPA) auth use @authaction/web-sdk.
For API JWT verification use @authaction/node-sdk.

Installation

npm install @authaction/server-sdk

How it works

GET /auth/login    → generate PKCE → store state + verifier in cookie → redirect to AuthAction
GET /auth/callback → validate state → exchange code for tokens → set encrypted session cookie
GET /auth/logout   → clear session cookie → redirect to AuthAction /oauth2/logout

Access tokens are refreshed on demand, not automatically. The session cookie lives seven days; an access token about an hour. Call getAccessToken where you need one and it refreshes when the stored one has expired:

// Next.js route handler
const fresh = await getAccessToken(req, config);
if (!fresh) return new Response(null, { status: 401 });   // sign in again

const res = Response.json(await callYourApi(fresh.accessToken));
if (fresh.setCookie) res.headers.set('Set-Cookie', fresh.setCookie);
return res;

AuthAction rotates refresh tokens — a refresh returns a new one and invalidates the old — so the refreshed session has to be persisted. Next.js and Remix hand you a setCookie to attach to the response you are returning, because they are given a bare Request and own no response. SvelteKit and Nuxt write the cookie themselves, since their event owns one, and return the token alone. That is also why refreshing is not hidden inside getSession: a read owns no response, so a refresh it could not persist would work once and break the request after it.

Sessions are stored as JWE-encrypted HTTP-only cookies (AES-256-GCM, key derived from sessionSecret).

Logout ends the session at both ends. The session keeps the ID token from the login that opened it, and logout sends it as id_token_hint. AuthAction matches that token's sid claim against the session behind its own cookie and ends nothing without it — so a logout that omits the hint clears the application's cookie, redirects home, and leaves single sign-on open, with the next sign-in needing no credentials. A session written before this SDK kept the ID token carries none; logout still clears and still redirects, which is the best that can be done for it.


Next.js

1. Create the catch-all route handler

// app/api/auth/[...authaction]/route.ts
import { createNextHandlers } from '@authaction/server-sdk/nextjs';

export const { GET } = createNextHandlers({
  domain:               process.env.AUTHACTION_DOMAIN!,
  clientId:             process.env.AUTHACTION_CLIENT_ID!,
  clientSecret:         process.env.AUTHACTION_CLIENT_SECRET,
  redirectUri:          process.env.AUTHACTION_REDIRECT_URI!,
  postLogoutRedirectUri: process.env.AUTHACTION_LOGOUT_REDIRECT_URI,
  sessionSecret:        process.env.SESSION_SECRET!,
});

Handles automatically:

  • GET /api/auth/login → redirect to AuthAction
  • GET /api/auth/callback → exchange code, set session
  • GET /api/auth/logout → clear session, redirect to AuthAction

2. Protect routes with middleware

// middleware.ts
import { createAuthMiddleware } from '@authaction/server-sdk/nextjs';

export default createAuthMiddleware({
  sessionSecret:  process.env.SESSION_SECRET!,
  protectedPaths: ['/dashboard', '/profile'],
  loginPath:      '/api/auth/login',
});

export const config = { matcher: ['/dashboard/:path*', '/profile/:path*'] };

3. Read the session in Server Components

// app/dashboard/page.tsx
import { getSessionFromRequest } from '@authaction/server-sdk/nextjs';
import { cookies } from 'next/headers';

export default async function DashboardPage() {
  // Option A — via route handler request object
  // Option B — build a request from cookies for server components
  const session = ...; // use getSessionFromRequest(req, config)
  if (!session) redirect('/api/auth/login');
  return <div>Hello {session.user.name}</div>;
}

Remix

// app/auth.server.ts
import { createRemixAuth } from '@authaction/server-sdk/remix';

export const auth = createRemixAuth({
  domain:        process.env.AUTHACTION_DOMAIN!,
  clientId:      process.env.AUTHACTION_CLIENT_ID!,
  redirectUri:   process.env.AUTHACTION_REDIRECT_URI!,
  sessionSecret: process.env.SESSION_SECRET!,
});
// app/routes/auth.login.tsx
export const loader = ({ request }: LoaderFunctionArgs) => auth.handleLogin(request);

// app/routes/auth.callback.tsx
export const loader = ({ request }: LoaderFunctionArgs) => auth.handleCallback(request);

// app/routes/auth.logout.tsx
export const action = ({ request }: ActionFunctionArgs) => auth.handleLogout(request);

// app/routes/dashboard.tsx
export async function loader({ request }: LoaderFunctionArgs) {
  const session = await auth.requireSession(request); // redirects to /auth/login if missing
  return { user: session.user };
}

Nuxt

// server/api/auth/[...].ts
import { createNuxtHandlers } from '@authaction/server-sdk/nuxt';
import { defineEventHandler, getCookie, setCookie, deleteCookie, getQuery, sendRedirect, createError } from 'h3';

const { handler } = createNuxtHandlers(
  {
    domain:        process.env.AUTHACTION_DOMAIN!,
    clientId:      process.env.AUTHACTION_CLIENT_ID!,
    redirectUri:   process.env.AUTHACTION_REDIRECT_URI!,
    sessionSecret: process.env.SESSION_SECRET!,
  },
  { defineEventHandler, getCookie, setCookie, deleteCookie, getQuery, sendRedirect, createError },
);

export default handler;

Handles: /api/auth/login, /api/auth/callback, /api/auth/logout, /api/auth/session


SvelteKit

// src/lib/auth.server.ts
import { createSvelteAuth } from '@authaction/server-sdk/svelte';
import { env } from '$env/dynamic/private';

export const auth = createSvelteAuth({
  domain:        env.AUTHACTION_DOMAIN,
  clientId:      env.AUTHACTION_CLIENT_ID,
  redirectUri:   env.AUTHACTION_REDIRECT_URI,
  sessionSecret: env.SESSION_SECRET,
});
// src/routes/auth/login/+server.ts
import { auth } from '$lib/auth.server';
export const GET = (event) => auth.handleLogin(event);

// src/routes/auth/callback/+server.ts
export const GET = (event) => auth.handleCallback(event);

// src/routes/auth/logout/+server.ts
export const GET = (event) => auth.handleLogout(event);

// src/hooks.server.ts — populates event.locals.session on every request
import { auth } from '$lib/auth.server';
export const handle = auth.handle;

// src/routes/dashboard/+page.server.ts
export async function load({ locals }) {
  if (!locals.session) throw redirect(302, '/auth/login');
  return { user: locals.session.user };
}

Configuration

Option Required Description
domain ✓ AuthAction tenant domain
clientId ✓ OAuth2 client ID
clientSecret Client secret (recommended for server apps)
redirectUri ✓ Callback URL after login
postLogoutRedirectUri Where to return after logout. Defaults to the origin being served — and, on Nuxt, to the origin of redirectUri, since h3's event carries no host
sessionSecret ✓ Secret for session cookie encryption (32+ chars)
cookieName Session cookie name (default: __aa_session)
cookieMaxAge Session TTL in seconds (default: 7 days)
pkceMaxAge How long a login may take at the identity provider, in seconds (default: 1 hour)
loginRedirect Post-login redirect (default: /)

When a login comes back without its PKCE cookie

The verifier lives in a short-lived __aa_pkce cookie between /login and /callback. If it is not there when the callback arrives, the SDK does not report a failure straight away:

  • A session is already set — the callback is a second delivery of one that worked (a reload, a back button, a browser retry). The user is sent on to loginRedirect.
  • Otherwise — the login is started again once, automatically. The usual cause is a cookie that expired while the user was signing in at the identity provider; they are signed in there by now, so the retry costs a redirect and no interaction.
  • The retry also comes back without one — something is dropping the cookie for good (private browsing, a webview handing off to another browser, cookies refused), and the user lands on /?error=missing_pkce.

The retry is marked in the OAuth state rather than in a cookie of its own, so exactly one automatic retry can happen no matter what the browser does with storage. Raise pkceMaxAge if your users routinely take longer than an hour to get through the identity provider.

Session data

interface SessionData {
  user: {
    sub: string;
    name?: string;
    email?: string;
    [key: string]: unknown;
  };
  accessToken: string;
  refreshToken?: string;
  expiresAt: number; // Unix timestamp (ms)
}

Environment variables

AUTHACTION_DOMAIN=your-tenant.eu.authaction.com
AUTHACTION_CLIENT_ID=your-client-id
AUTHACTION_CLIENT_SECRET=your-client-secret   # optional
AUTHACTION_REDIRECT_URI=http://localhost:3000/auth/callback
AUTHACTION_LOGOUT_REDIRECT_URI=http://localhost:3000
SESSION_SECRET=a-random-string-at-least-32-characters-long

License

MIT

Related Packages

@proteles/vue

Vue 3 composables and components for Proteles authentication, plus Nuxt/h3 serve...

465 0
cauthy-auth

Sign in with Cauthy: one route to mount, getSession on the server, useSession in...

2,148
@wocha/nuxt

Nuxt 3 module for Wocha authentication (BFF pattern with httpOnly cookies)

599
@tktchurch/auth

Framework-agnostic auth SDK for TKTChurch OAuth/AuthFlow services

2,767
@authup/client-web-nuxt

Nuxt module that signs your app in with Authup and guards its routes by login st...

11,785 41

Version History

Version Released Vue License
0.2.0 ^3.0 MIT
0.1.2 ^3.0 MIT
0.1.1 ^3.0 MIT
0.1.0 ^3.0 MIT