Skip to main content

References: API & Middleware

Reference for exports, hooks, middleware options, and token verification helpers.

Package exports

  • <TideCloakProvider> - application‑level context
  • useTideCloak() - access tokens and auth actions
  • verifyTideCloakToken() - server‑side JWT verification
  • <Authenticated> / <Unauthenticated> - UI guards
  • doEncrypt() / doDecrypt() - tag‑based encryption/decryption
  • createTideCloakMiddleware() - Edge middleware for route protection

useTideCloak API

NameTypeDescription
authenticatedbooleanWhether the user is logged in.
login() / logout()() => voidTrigger the login or logout flows.
token, tokenExpstring, numberAccess token and its expiration timestamp.
Automatic token refreshbuilt‑inTokens refresh silently - no manual setup needed.
refreshToken()() => Promise<boolean>Force a silent token renewal.
getValueFromToken(key)(key: string) => anyRead a custom claim from the access token.
getValueFromIdToken(key)(key: string) => anyRead a custom claim from the ID token.
hasRealmRole(role)(role: string) => booleanCheck a realm‑level role.
hasClientRole(role, client?)(role: string, client?: string) => booleanCheck a client‑level role; defaults to your app’s client ID if omitted.
doEncrypt(data) / doDecrypt(data)(data: any) => Promise<any>Encrypt/decrypt payloads via TideCloak’s service.

Encrypt/Decrypt syntax overview

// Encrypt payloads:
const encryptedArray = await doEncrypt([
{ data: /* string | Uint8Array */, tags: ['tag1', 'tag2'] },
]);

// Decrypt blobs:
const decryptedArray = await doDecrypt([
{ encrypted: /* string from doEncrypt */, tags: ['tag1', 'tag2'] },
]);
  • Permissions: _tide_<tag>.selfencrypt to encrypt; _tide_<tag>.selfdecrypt to decrypt.
  • Order guarantee: returned array preserves input order.

Guard components

import { Authenticated, Unauthenticated } from '@tidecloak/nextjs';
  • <Authenticated> renders children only when authenticated === true
  • <Unauthenticated> renders children only when authenticated === false

Edge middleware

Create middleware with:

import { createTideCloakMiddleware } from '@tidecloak/nextjs/server/tidecloakMiddleware';

Options

  • config (TidecloakConfig): TideCloak adapter JSON.
  • protectedRoutes (ProtectedRoutesMap): Map of path patterns to arrays of required roles.
  • onRequest(ctx, req): (ctx: { token: string | null }, req: NextRequest) => NextResponse | void
  • onSuccess(ctx, req): (ctx: { payload: Record<string, any> }, req: NextRequest) => NextResponse | void
  • onFailure(ctx, req): (ctx: { token: string | null }, req: NextRequest) => NextResponse | void
  • onError(err, req): (err: any, req: NextRequest) => NextResponse

Typical matcher/export

export const config = {
matcher: [
'/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)',
'/api/(.*)',
],
runtime: 'edge',
};

Server‑side verification

import { verifyTideCloakToken } from '@tidecloak/nextjs/server';

// Returns decoded payload if valid & roles pass, otherwise null
const payload = await verifyTideCloakToken(
config, // adapter JSON
token, // raw access token
['admin','user'] // optional roles (at least one must match)
);

Parameters

  • config (object): parsed Keycloak config (adapter JSON).
  • token (string): access token to verify.
  • allowedRoles (string[], optional): realm or client roles; user must have at least one.

Returns

  • Promise<object | null> - decoded JWT payload if valid and role check passes; otherwise null.