Quick start for Next.js
Add MainSDK to a Next.js App Router app, guard one route with auth.require, run it in local mode with a test user and pass mainsdk check.
Status Status is where the work is: Planned (in a milestone, not started), Building (tickets in progress), Preview (usable, may change), then the stability it ships at.
Stability The promise an interface ships with.
- Stable Follows semantic versioning; breaking changes need a new major, 12 months of overlap and a codemod.
- Beta Usable in production; may change before it becomes stable.
- Experimental May change or go away; needs an explicit opt-in in main.yaml.
You will add MainSDK to a Next.js app, guard one route and run it with no account or key. It takes about 10 minutes. Next.js support covers the App Router.
1. Initialise
Run this in the root of a Next.js app. It writes main.yaml with local drivers and tells your coding agent the rules.
npx mainsdk init2. Mount MainSDK
import { mainsdk } from 'mainsdk/next'
export const proxy = mainsdk.proxy()3. Guard a route
import { auth } from 'mainsdk'
import { withMainSDK } from 'mainsdk/next'
// One route that needs a signed-in user: anyone else gets a 401 problem with a fix.
export const GET = withMainSDK(async (req) => {
const session = await auth.require(req)
return Response.json({ user: session.user })
})4. Run it in local mode
In local mode the bearer token dev_ada stands for a test person called ada. It works only on loopback, under mainsdk dev.
npx mainsdk dev -- npm run dev
curl -i localhost:3000/api/me
curl -i -H "Authorization: Bearer dev_ada" localhost:3000/api/meThe first call answers 401 with a problem body that carries MAIN-AUTH-0001 and a fix. The second answers 200 with the user.
Check it
npx mainsdk checkThe check passes when it prints Passed. It fails on a key in code, an undeclared network call or an unguarded action, and names the fix for each. Run it in CI too.
What the sample app is
The finished app is in the repository under apps/examples/nextjs. CI installs it, starts it in local mode, requests the signed-in route and runs mainsdk check, so these steps cannot drift from the code. MainSDK is pre-release and no package is published yet: until the first beta, run the sample from a checkout.
Was this page helpful?