@grantry/nextjs
v0.4.2
Published
Grantry authentication for Next.js: the React components and hooks, server-side auth() and route-protecting middleware.
Maintainers
Readme
@grantry/nextjs
Grantry authentication for Next.js: the React components and hooks, auth() for server
components, route handlers and server actions, and a middleware that keeps signed-out visitors
off protected routes.
npm install @grantry/nextjsRequires Next.js 15 or 16 and React 18 or 19. Everything @grantry/react exports is
re-exported here, so a Next.js application does not install it separately.
Setup
Set your publishable key (Grantry dashboard, API keys):
NEXT_PUBLIC_GRANTRY_PUBLISHABLE_KEY=pk_live_...Wrap the application in the provider:
// app/layout.tsx
import { GrantryProvider } from '@grantry/nextjs';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<GrantryProvider publishableKey={process.env.NEXT_PUBLIC_GRANTRY_PUBLISHABLE_KEY!}>
{children}
</GrantryProvider>
</body>
</html>
);
}Reading the visitor on the server
import { auth } from '@grantry/nextjs/server';
export default async function Page() {
const { userId } = await auth();
if (!userId) return <p>Signed out</p>;
return <p>Signed in as {userId}</p>;
}auth() verifies the grantry_token cookie against Grantry's published signing keys, which are
fetched once and cached; no request is made per render after that. It checks the signature, the
expiry, the issuer and that the token belongs to your application, read from the publishable
key. With no publishable key configured it throws no_audience rather than accept a token minted
for another application.
requireAuth() is the same but throws when nobody is signed in. For the Pages Router, or anything
else that cannot call next/headers, verify the cookie yourself with verifyToken, which is also
exported from @grantry/nextjs/server.
Selling
<PricingTable>, <ProductCard> and <CheckoutButton> sell through Grantry's hosted checkout: the
browser leaves for a page on your application's checkout domain and comes back once it is paid. Since
0.2.0 it is the only checkout; the in-app checkout dialog is gone. To make one from a route handler or
a server action:
// app/api/checkout/route.ts
import { auth, createCheckoutSession } from '@grantry/nextjs/server';
export async function POST() {
const { userId } = await auth();
if (!userId) return new Response(null, { status: 401 });
const checkout = await createCheckoutSession({
userId,
items: [{ priceId: 'price_…' }],
successUrl: 'https://example.com/thanks',
});
// The URL carries the checkout's key: redirect to it, never log it.
return Response.redirect(checkout.url, 303);
}It reads your secret key from GRANTRY_SECRET_KEY, on the server only.
Protecting routes
// proxy.ts (Next.js 16) or middleware.ts (Next.js 15)
import { grantryMiddleware } from '@grantry/nextjs/middleware';
export default grantryMiddleware({
protectedRoutes: ['/dashboard', '/account'],
signInUrl: '/sign-in',
});
export const config = { matcher: ['/((?!_next|.*\\..*).*)'] };A string protects that path and everything under it; pass a RegExp for anything else. Only what
is listed is protected. A signed-out visitor is redirected to the sign-in page with redirect_url
set to where they were going. A verified request goes on with x-grantry-user-id and
x-grantry-session-id set; those headers are removed from every request the middleware sees, but
a route outside the matcher never reaches it, so auth() is the safer read.
With no signInUrl, the middleware uses GRANTRY_SIGN_IN_URL, then
NEXT_PUBLIC_GRANTRY_SIGN_IN_URL, then the environment's hosted sign-in page, and answers 401
if there is none.
Environment variables
| Variable | Read by |
| --- | --- |
| NEXT_PUBLIC_GRANTRY_PUBLISHABLE_KEY | auth(), the middleware (and pass it to the provider) |
| GRANTRY_PUBLISHABLE_KEY | auth() and the middleware, before the public one |
| NEXT_PUBLIC_GRANTRY_SIGN_IN_URL | the provider and the middleware (after GRANTRY_SIGN_IN_URL) |
| NEXT_PUBLIC_GRANTRY_SIGN_UP_URL | the provider |
| NEXT_PUBLIC_GRANTRY_SIGN_IN_FALLBACK_REDIRECT_URL, ..._SIGN_UP_FALLBACK_REDIRECT_URL | the provider |
| NEXT_PUBLIC_GRANTRY_SIGN_IN_FORCE_REDIRECT_URL, ..._SIGN_UP_FORCE_REDIRECT_URL | the provider |
| NEXT_PUBLIC_GRANTRY_AFTER_SIGN_OUT_URL | the provider |
| GRANTRY_SECRET_KEY | createCheckoutSession and verifyReverification, on the server |
Nothing else here reads a secret key; never give it a NEXT_PUBLIC_ name.
About the token cookie
The browser SDK mirrors the short-lived access token into a grantry_token cookie on your domain
(SameSite=Lax, Secure on HTTPS) so the server can see who is signed in. A cookie written by
script cannot be httpOnly; the token lives about a minute and cannot mint another, and the
credential that can stays httpOnly on Grantry's domain.
License
MIT
