@githat/nextjs
v0.21.2
Published
GitHat identity SDK for Next.js applications
Readme
@githat/nextjs
The GitHat identity SDK for Next.js and React.
Drop sign-in, sign-up, route protection, and organizations into your app.
GitHat is the backend (api.githat.io) — there is nothing to deploy.
Quick Start · Components · Server-Side Auth · Docs
Which GitHat package do I need?
GitHat ships two npm packages. They do different jobs — pick by what you're doing:
| If you want to… | Use | How |
|---|---|---|
| Add GitHat auth to an app you already have | @githat/nextjs — this package | npm install @githat/nextjs |
| Start a brand-new app pre-wired with GitHat | create-githat-app | npx create-githat-app |
@githat/nextjs is the runtime SDK — the components, hooks, and middleware you import in your code, on every build. create-githat-app is a one-time scaffolding CLI that generates a new project with this SDK already installed and wired up. It's the same relationship as next and create-next-app.
Adding auth to an existing codebase? This package is what you want.
Features
- Pre-built UI — themed sign-in, sign-up, password reset, and email verification
- React hooks —
useAuth()for auth state,useGitHat()for authenticated API calls - Edge route protection — one line of middleware (
authMiddleware/authProxy) - Server-side auth —
verifyToken,getAuth,withAuthfor API routes - Multi-tenant — organizations, invitations, and roles, managed by GitHat
- Local JWT verification — RS256 tokens verify against the JWKS at
api.githat.io/.well-known/jwks.json: no shared secret, no per-request round-trip - TypeScript-first, ships ESM + CJS
Quick Start
1. Install
npm install @githat/nextjs2. Wrap your app
Grab your publishable key from the GitHat dashboard, then:
// app/layout.tsx
import { GitHatProvider } from '@githat/nextjs';
import '@githat/nextjs/styles';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<GitHatProvider
config={{
publishableKey: process.env.NEXT_PUBLIC_GITHAT_KEY!,
afterSignInUrl: '/dashboard',
}}
>
{children}
</GitHatProvider>
</body>
</html>
);
}3. Add auth pages
// app/sign-in/page.tsx
import { SignInForm } from '@githat/nextjs';
export default function Page() {
return <SignInForm signUpUrl="/sign-up" forgotPasswordUrl="/forgot-password" />;
}SignUpForm, ForgotPasswordForm, ResetPasswordForm, and VerifyEmailStatus drop in the same way.
4. Protect routes
// proxy.ts — Next.js 16+ (on Next.js 14–15: middleware.ts + authMiddleware)
import { authProxy } from '@githat/nextjs/proxy';
export const proxy = authProxy({
publicRoutes: ['/', '/sign-in', '/sign-up', '/forgot-password'],
});
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};5. Read auth state anywhere
'use client';
import { useAuth, UserButton, OrgSwitcher } from '@githat/nextjs';
export function Header() {
const { user, isSignedIn } = useAuth();
if (!isSignedIn) return null;
return (
<header>
<span>Welcome, {user?.name}</span>
<OrgSwitcher />
<UserButton />
</header>
);
}That's a fully authenticated app — sign-in, sign-up, route protection, and org switching.
Components
Import the dark theme once (import '@githat/nextjs/styles'). Every class is githat--prefixed, so it never collides with your styles; override with normal CSS specificity.
| Component | Purpose |
|---|---|
| GitHatProvider | Wraps your app, provides auth context (required) |
| SignInForm / SignUpForm | Email + password auth forms |
| ForgotPasswordForm / ResetPasswordForm | Request and complete a password reset |
| VerifyEmailStatus | Auto-verifies an email token from the URL |
| ChangePasswordForm | Change password for a signed-in user |
| SignInButton / SignUpButton | Links to your auth pages |
| UserButton | Avatar dropdown with user info + sign-out |
| OrgSwitcher | Switch between organizations |
| ProtectedRoute | Client-side redirect for unauthenticated users |
| VerifiedBadge | Agent verification status badge |
Full prop tables and worked examples: githat.io/docs.
Hooks
useAuth() — auth state + actions
Must be used within <GitHatProvider>.
const {
user, org, isSignedIn, isLoading, authError, // state
signIn, signUp, signOut, switchOrg, // actions
} = useAuth();useGitHat() — authenticated API client
Tokens attach automatically.
const {
fetch, getUserOrgs, verifyAgent,
getOrgMetadata, updateOrgMetadata,
forgotPassword, resetPassword, changePassword,
verifyEmail, resendVerificationEmail,
} = useGitHat();
// Authenticated request — token attached for you
const { apps } = await fetch<{ apps: App[] }>('/user/apps');Next.js config — withGitHat()
Wrap next.config so the SDK's required CSP entry (connect-src https://api.githat.io) is injected. Without it the browser blocks every SDK request, which surfaces as the misleading "API request failed — verify your publishable key" error.
// next.config.ts
import { withGitHat } from '@githat/nextjs/server';
export default withGitHat({ output: 'standalone' });Options (extraConnectSrc, extraImgSrc, csp, securityHeaders, …) merge with any headers() you already have — they never replace it. CSP is env-aware: development adds 'unsafe-eval' for Next.js HMR, production omits it.
Middleware & Proxy
authMiddleware (Next.js 14–15, middleware.ts) and authProxy (Next.js 16+, proxy.ts) protect routes at the edge and accept the same options:
| Option | Type | Default | Description |
|---|---|---|---|
| publicRoutes | string[] | ['/'] | Routes reachable without auth (supports /prefix/*) |
| signInUrl | string | '/sign-in' | Where to send unauthenticated users |
| injectHeaders | boolean | false | Inject x-githat-* headers (user id, email, org id, org slug, role) |
| tokenCookie | string | 'githat_access' | Access-token cookie name |
API routes are not protected by the middleware/proxy. Both skip
/apiby design — protect handlers explicitly withwithAuth()/getAuth()(below).
Server-Side Auth
@githat/nextjs/server verifies tokens in API routes and Server Components. Verification is local against the GitHat JWKS — fast, and with no shared secret to drift.
import { withAuth, getAuth, verifyToken } from '@githat/nextjs/server';
// Wrap a route — the handler runs only with a valid token
export const GET = withAuth(async (request, auth) => {
return Response.json({ userId: auth.userId, orgId: auth.orgId });
});| Export | Purpose |
|---|---|
| verifyToken(token, options?) | Verify a JWT → AuthPayload. Options: { apiUrl?, audience? } |
| getAuth(request, options?) | Extract + verify the token from a request (cookie, then Authorization header) |
| withAuth(handler, options?) | Wrap a route handler; rejects unauthenticated requests |
| getOrgMetadata / updateOrgMetadata | Server-side org metadata read/write |
| COOKIE_NAMES | { accessToken: 'githat_access', refreshToken: 'githat_refresh' } |
AuthPayload shape: { userId, email, orgId, orgSlug, role, tier }.
verifyToken defaults apiUrl to https://api.githat.io and pins the token issuer to it automatically — override apiUrl only when self-hosting the GitHat backend.
Configuration
Pass config to <GitHatProvider>:
| Property | Type | Required | Default |
|---|---|---|---|
| publishableKey | string | yes | — |
| apiUrl | string | no | https://api.githat.io |
| signInUrl / signUpUrl | string | no | /sign-in / /sign-up |
| afterSignInUrl / afterSignOutUrl | string | no | / |
| tokenStorage | 'localStorage' \| 'cookie' | no | 'localStorage' |
Use tokenStorage: 'cookie' (httpOnly, XSS-resistant) for apps with server-side rendering — it's required for the getAuth() / withAuth() server utilities.
# .env.local
NEXT_PUBLIC_GITHAT_KEY=pk_live_your_key_hereThe SDK runs in any React 18+ app — for Vite or CRA, wrap your root in GitHatProvider the same way. The middleware/proxy exports are Next.js-only; elsewhere use <ProtectedRoute> for client-side protection.
Compatibility
| Runtime | Version | Support | |---|---|---| | Next.js (App Router) | ≥ 14 | Full | | Next.js (Pages Router) | ≥ 14 | Components + hooks | | React — Vite / CRA | ≥ 18 | Components + hooks |
Known Limitations
Not blockers — each has a documented workaround at githat.io/docs:
- No webhooks / event system — use the
onSuccesscallback on form components to call your own API on sign-up, verification, etc. - No per-user metadata API — org metadata exists; store per-user data in your own database, keyed by the GitHat user id.
- No bulk user import — users re-register; contact us for enterprise migrations.
- API routes aren't auto-protected — protect each one with
withAuth()/getAuth().
Links
- Documentation · Dashboard
create-githat-app— scaffold a new GitHat app- Report an issue
License
Proprietary. © GitHat Inc.
