Authentication
Next.js and React
Ready-made auth routes, middleware guard, and React hooks for Buildspace sessions.
@buildspacestudio/sdk/next and @buildspacestudio/sdk/react replace the hand-written callback, session, and logout routes. Everything uses the bs_session cookie. The handlers use web-standard Request/Response, so they work in any framework that does.
Routes (@buildspacestudio/sdk/next)
// app/api/auth/callback/route.ts
import { createAuthCallback } from "@buildspacestudio/sdk/next";
import { getServerClient } from "@/lib/buildspace";
export const GET = createAuthCallback(getServerClient(), {
redirectTo: "/dashboard",
onSignIn: async ({ user }) => upsertUser(user), // failures are logged, never block login
});// app/api/auth/logout/route.ts
export const POST = createLogoutRoute(getServerClient());
// app/api/auth/session/route.ts
export const GET = createSessionRoute(getServerClient()); // { session } without the raw token| Export | Purpose |
|---|---|
createAuthCallback(client, { redirectTo?, onSignIn?, onError?, cookie? }) | Exchanges ?code=, sets the cookie, redirects |
createLogoutRoute(client) | Revokes the session and clears the cookie |
createSessionRoute(client) | Returns the current session, safe for the browser |
getSession(client, source) / requireSession(client, source) | Read the bs_session cookie from a Request or await cookies() and validate it. getSession returns null when signed out; requireSession throws a 401 BuildspaceError |
createSessionCookieGuard({ redirectTo? }) | Middleware presence check that redirects signed-out requests |
The cookie guard is only a fast presence check. Pages and route handlers must still validate with getSession.
// proxy.ts
import { createSessionCookieGuard } from "@buildspacestudio/sdk/next";
export const proxy = createSessionCookieGuard({ redirectTo: "/" });
export const config = { matcher: ["/dashboard/:path*"] };React (@buildspacestudio/sdk/react)
Requires react >= 19. Mount the provider in a client boundary and pass the user resolved on the server so the first render has no loading flash.
"use client";
import { createClient } from "@buildspacestudio/sdk/client";
import { BuildspaceProvider } from "@buildspacestudio/sdk/react";
const client = createClient(process.env.NEXT_PUBLIC_BUILDSPACE_PUBLISHABLE_KEY!);
export function Providers({ children, initialUser }) {
return (
<BuildspaceProvider client={client} initialUser={initialUser}>
{children}
</BuildspaceProvider>
);
}| Hook | Returns |
|---|---|
useAuth() | { user, loading, signIn, signUp, signOut } |
useSession() | { user, loading } |
useBuildspaceClient() | The client SDK instance |
useTrack() | track(event, properties?) — never throws, bound to the signed-in user |
useUpload({ endpoint? }) | Browser uploads, see Storage client SDK |
BuildspaceProvider defaults: callbackPath="/api/auth/callback", logoutPath="/api/auth/logout", signedOutRedirect="/".