Use Basalt with Next.js
Learn how to create a Basalt project, add some sample data, and query it from a Next.js app.
Help me add Basalt to my Next.js project. Create a project, run the `notes` table SQL below, install @basalt/client, put BASALT_URL and BASALT_PUBLISHABLE_KEY in .env.local, then render the rows on /notes.Create a Basalt project
Create a new project from the dashboard of any team you belong to. Give it a name, pick the region nearest your users, and save the database password somewhere safe.
Want to create a project programmatically? Use the Management API or the
basalt projects createcommand.Set up your database
Open the SQL editor and run the snippet below. It creates a
notestable, adds two rows, and turns on row-level policies so only the right people can read it.notes.sql create table notes ( id bigint primary key generated always as identity, body text not null, created_at timestamptz default now());insert into notes (body)values ('Pour the foundation'), ('Frame the walls');alter table notes enable row level security;create policy "public can read notes"on notes for select to anonusing (true);Create a Next.js app
Scaffold a new app from the official starter.
- npm
- pnpm
- yarn
npx create-next-app@latest basalt-notes --typescriptpnpm create next-app basalt-notes --typescriptyarn create next-app basalt-notes --typescriptDeclare environment variables
Copy the project URL and the publishable key from Project settings → API into
.env.local..env.local NEXT_PUBLIC_BASALT_URL=https://abcd1234.basalt.run NEXT_PUBLIC_BASALT_PUBLISHABLE_KEY=bpk_live_xxxxxxxxxxxxxxxxQuery Basalt data from Next.js
Create a server component that reads the table.
app/notes/page.tsx import { createClient } from '@basalt/client'export default async function Notes() { const basalt = createClient(process.env.NEXT_PUBLIC_BASALT_URL!, process.env.NEXT_PUBLIC_BASALT_PUBLISHABLE_KEY!) const { data: notes } = await basalt.from('notes').select() return <pre>{JSON.stringify(notes, null, 2)}</pre>}Start the app
Run
npm run devand open http://localhost:3000/notes. You should see both rows.
Production requirements
Setting | Development | Production |
|---|---|---|
Key | Publishable | Publishable (browser), secret (server only) |
Row-level policies | Optional | Required on every exposed table |
Connection | Direct | Pooled, transaction mode |
Next steps
Add sign-in with Password sign-in.
Read about Row-level policies before you ship.