Call Gridsay from the browser.
A publishable key lets your page call Gridsay directly, without a route on your server. Because the key is in your page, anyone can copy it, so every request must also carry a verified user: a token from your sign-in, which Gridsay checks. Each user is then counted against limits you set.
Use this when your grid faces your customers and you want each of them limited and reported separately, or when you would rather not run a route. If you are moving from MUI’s hosted service, start with the server quickstart instead: it is a smaller change.
1. Create a publishable key.
In the dashboard, open Keys, choose Create key and the type Publishable. List every origin your grid runs on, such as https://app.example.com. Add http://localhost:3000 (or your development port) as well: publishable keys have no exception for local development.
The key refuses every request until it has an end-user authentication method. That is the next step.
2. Choose how we verify your users.
Open Authentication in the dashboard and choose the key. Pick one of three methods.
Use this if your sign-in already issues JWTs: Clerk, Auth0, Supabase, Firebase, Cognito, Microsoft Entra ID, Okta, WorkOS, Better Auth and most others do. Enter:
- your provider’s issuer (we read its signing keys from its OpenID configuration), or a JWKS URL;
- the audience your tokens are issued for. If your provider adds no audience by default, the dashboard says where to set one;
- the claim that holds the user id (
subunless you change it).
Tokens signed with a shared HS256 secret also work: enter the secret once, at least 32 characters. We store it encrypted and never show it again.
Use this if your app has no JWTs. Your server asks Gridsay for a short-lived token for the signed-in user, using a secret key, and passes it to the browser:
import { NextResponse } from 'next/server'; export async function POST() { const user = await getSignedInUser(); // your own sign-in if (!user) return NextResponse.json({ error: 'Not signed in' }, { status: 401 }); const response = await fetch(`${process.env.GRIDSAY_URL}/api/v1/sessions`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.GRIDSAY_API_KEY!, // a secret key }, body: JSON.stringify({ userId: user.id, attributes: { plan: user.plan }, // optional; your limit rules can match on these ttlSeconds: 3600, // 60 to 86,400; default 3,600 }), }); // On success: { ok: true, data: { token, expiresAt } } return NextResponse.json(await response.json(), { status: response.status });}Use this if your server can answer “who is this?” for a value your page already has. Enter your endpoint’s URL (HTTPS), the request header your page sets that we should forward (not cookie: the browser does not send cookies to us), and how long we may cache the answer (0 to 3,600 seconds, default 60). Then create the signing secret; it is shown once.
For each new credential we POST { "credential": "<the header's value>" } to your endpoint, signed. Answer 200 with the user, or 401 if the credential is not valid:
import { createHmac, timingSafeEqual } from 'node:crypto'; export async function POST(request: Request) { const body = await request.text(); const signature = request.headers.get('x-gridsay-signature') ?? ''; const t = /t=(\d+)/.exec(signature)?.[1]; const v1 = /v1=([0-9a-f]+)/.exec(signature)?.[1]; const expected = createHmac('sha256', process.env.GRIDSAY_WEBHOOK_SECRET!) .update(`${t}.${body}`) .digest('hex'); const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300; if (!t || !v1 || !fresh || v1.length !== expected.length || !timingSafeEqual(Buffer.from(v1), Buffer.from(expected))) { return new Response(null, { status: 401 }); } const { credential } = JSON.parse(body); const user = await findUserByCredential(credential); // your own lookup if (!user) return new Response(null, { status: 401 }); return Response.json({ userId: user.id, attributes: { plan: user.plan } });}attributes is required; send {} if you have nothing to add.
Custom methods, built with you, are available on Enterprise.
3. Set limits.
Still under Authentication, add limits. Limits for the whole key apply across all users. Below them, rules apply per user, in order; the first rule whose condition matches a user applies to that user. A rule can test one claim from the token (or one attribute from your webhook or session token), and sets limits per minute, hour, day or calendar month (UTC). A rule can also read the monthly limit from a claim, so your own system decides each customer’s quota.
Give each rule a message. It is what your user reads in the assistant panel when they reach the limit, so it can point to your upgrade page. End with a rule that has no condition: it catches everyone else.
| Order | Users | Limit | What they see at the limit |
|---|---|---|---|
| 1 | whose plan is enterprise | 60 a minute, 5,000 a month | the default message, with when to try again |
| 2 | whose email ends with @yourcompany.com | 120 a minute | the default message |
| 3 | everyone else | 10 a minute, 50 a day, 300 a month | “You have used this month’s AI questions. Upgrade to continue.” |
4. Connect the grid.
Install our browser helper:
npm install @gridsay/clientpnpm add @gridsay/clientyarn add @gridsay/clientbun add @gridsay/clientThen use it as the grid’s onPrompt. url is your gateway address followed by the prompt path; getToken returns your user’s token for every request.
import { createPromptResolver } from '@gridsay/client';import { DataGridPremium, type DataGridPremiumProps, useGridApiRef } from '@mui/x-data-grid-premium';import { useMemo } from 'react'; export function OrdersGrid({ rows, columns }: Pick<DataGridPremiumProps, 'rows' | 'columns'>) { const apiRef = useGridApiRef(); const onPrompt = useMemo( () => createPromptResolver({ url: `${process.env.NEXT_PUBLIC_GRIDSAY_URL}/api/v1/datagrid/prompt`, publishableKey: process.env.NEXT_PUBLIC_GRIDSAY_PUBLISHABLE_KEY!, getToken: getUserToken, // your sign-in's token, or a session token from your route apiRef, }), [apiRef], ); return <DataGridPremium apiRef={apiRef} rows={rows} columns={columns} aiAssistant onPrompt={onPrompt} />;}With session tokens, getUserToken can call the route from step 2 and return data.token; keep it until expiresAt rather than minting one for every question. With the webhook method and a header other than authorization, leave out getToken and pass the header with headers instead.
If getToken throws or returns nothing, nothing is sent and the panel shows “Sign in to use the assistant.”
5. Try it.
Open the grid while signed in to your app and ask a question. Then check the three refusals that protect you:
- signed out, the panel says “Sign in to use the assistant.”;
- from an origin that is not on the key’s list, it says “The assistant is not available on this site.”;
- past a limit, it shows your rule’s message.
Each request appears in the request log on the Usage page with the user it was counted against.
How limits, identity checks and answer checking fit together is on the “How it works” page. What a request sends and what we store is on the data and security page.