-
Notifications
You must be signed in to change notification settings - Fork 680
Quickstart nextjs #4097
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bradleyshep
wants to merge
10
commits into
master
Choose a base branch
from
quickstart-nextjs
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Quickstart nextjs #4097
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0136d60
init
bradleyshep 534a1c6
prettier
bradleyshep f0807d6
Update templates-list.json
bradleyshep e11d291
Merge branch 'master' into quickstart-nextjs
bradleyshep 8fcb0fa
Update 00200-nextjs.md
bradleyshep bca0e36
refinements
bradleyshep 8290040
Update providers.tsx
bradleyshep 8adab58
rename
bradleyshep eaf70b1
Update providers.tsx
bradleyshep 6a83a2a
Merge branch 'master' into quickstart-nextjs
bradleyshep File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
201 changes: 201 additions & 0 deletions
201
docs/docs/00100-intro/00200-quickstarts/00150-nextjs.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| --- | ||
| title: Next.js Quickstart | ||
| sidebar_label: Next.js | ||
| slug: /quickstarts/nextjs | ||
| hide_table_of_contents: true | ||
| --- | ||
|
|
||
| import { InstallCardLink } from "@site/src/components/InstallCardLink"; | ||
| import { StepByStep, Step, StepText, StepCode } from "@site/src/components/Steps"; | ||
|
|
||
|
|
||
| Get a SpacetimeDB Next.js app running in under 5 minutes. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - [Node.js](https://nodejs.org/) 18+ installed | ||
| - [SpacetimeDB CLI](https://spacetimedb.com/install) installed | ||
|
|
||
| <InstallCardLink /> | ||
|
|
||
| --- | ||
|
|
||
| <StepByStep> | ||
| <Step title="Create your project"> | ||
| <StepText> | ||
| Run the `spacetime dev` command to create a new project with a SpacetimeDB module and Next.js client. | ||
|
|
||
| This will start the local SpacetimeDB server, publish your module, generate TypeScript bindings, and start the Next.js development server. | ||
| </StepText> | ||
| <StepCode> | ||
| ```bash | ||
| spacetime dev --template nextjs-ts my-nextjs-app | ||
| ``` | ||
| </StepCode> | ||
| </Step> | ||
|
|
||
| <Step title="Open your app"> | ||
| <StepText> | ||
| Navigate to [http://localhost:3001](http://localhost:3001) to see your app running. | ||
|
|
||
| Note: The Next.js dev server runs on port 3001 to avoid conflict with SpacetimeDB on port 3000. | ||
| </StepText> | ||
| </Step> | ||
|
|
||
| <Step title="Explore the project structure"> | ||
| <StepText> | ||
| Your project contains both server and client code using the Next.js App Router. | ||
|
|
||
| Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `app/page.tsx` to build your UI. | ||
| </StepText> | ||
| <StepCode> | ||
| ``` | ||
| my-nextjs-app/ | ||
| ├── spacetimedb/ # Your SpacetimeDB module | ||
| │ └── src/ | ||
| │ └── index.ts # Server-side logic | ||
| ├── app/ # Next.js App Router | ||
| │ ├── layout.tsx # Root layout with providers | ||
| │ ├── page.tsx # Home page | ||
| │ └── providers.tsx # SpacetimeDB provider (client component) | ||
| ├── src/ | ||
| │ └── module_bindings/ # Auto-generated types | ||
| └── package.json | ||
| ``` | ||
| </StepCode> | ||
| </Step> | ||
|
|
||
| <Step title="Understand tables and reducers"> | ||
| <StepText> | ||
| Open `spacetimedb/src/index.ts` to see the module code. The template includes a `person` table and two reducers: `add` to insert a person, and `say_hello` to greet everyone. | ||
|
|
||
| Tables store your data. Reducers are functions that modify data — they're the only way to write to the database. | ||
| </StepText> | ||
| <StepCode> | ||
| ```typescript | ||
| import { schema, table, t } from 'spacetimedb/server'; | ||
|
|
||
| export const spacetimedb = schema( | ||
| table( | ||
| { name: 'person', public: true }, | ||
| { | ||
| name: t.string(), | ||
| } | ||
| ) | ||
| ); | ||
|
|
||
| spacetimedb.reducer('add', { name: t.string() }, (ctx, { name }) => { | ||
| ctx.db.person.insert({ name }); | ||
| }); | ||
|
|
||
| spacetimedb.reducer('say_hello', (ctx) => { | ||
| for (const person of ctx.db.person.iter()) { | ||
| console.info(`Hello, ${person.name}!`); | ||
| } | ||
| console.info('Hello, World!'); | ||
| }); | ||
| ``` | ||
| </StepCode> | ||
| </Step> | ||
|
|
||
| <Step title="Test with the CLI"> | ||
| <StepText> | ||
| Use the SpacetimeDB CLI to call reducers and query your data directly. | ||
| </StepText> | ||
| <StepCode> | ||
| ```bash | ||
| # Call the add reducer to insert a person | ||
| spacetime call my-nextjs-app add Alice | ||
|
|
||
| # Query the person table | ||
| spacetime sql my-nextjs-app "SELECT * FROM person" | ||
| name | ||
| --------- | ||
| "Alice" | ||
|
|
||
| # Call say_hello to greet everyone | ||
| spacetime call my-nextjs-app say_hello | ||
|
|
||
| # View the module logs | ||
| spacetime logs my-nextjs-app | ||
| 2025-01-13T12:00:00.000000Z INFO: Hello, Alice! | ||
| 2025-01-13T12:00:00.000000Z INFO: Hello, World! | ||
| ``` | ||
| </StepCode> | ||
| </Step> | ||
|
|
||
| <Step title="Understand the provider pattern"> | ||
| <StepText> | ||
| SpacetimeDB is client-side only — it cannot run during server-side rendering. The `app/providers.tsx` file uses the `"use client"` directive and wraps your app with `SpacetimeDBProvider`. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment as on the Remix PR. |
||
|
|
||
| The template uses environment variables for configuration. Set `NEXT_PUBLIC_SPACETIMEDB_URI` and `NEXT_PUBLIC_SPACETIMEDB_MODULE` to override defaults. | ||
| </StepText> | ||
| <StepCode> | ||
| ```tsx | ||
| // app/providers.tsx | ||
| 'use client'; | ||
|
|
||
| import { useMemo } from 'react'; | ||
| import { SpacetimeDBProvider } from 'spacetimedb/react'; | ||
| import { DbConnection } from '../src/module_bindings'; | ||
|
|
||
| const URI = process.env.NEXT_PUBLIC_SPACETIMEDB_URI ?? 'ws://localhost:3000'; | ||
| const MODULE = process.env.NEXT_PUBLIC_SPACETIMEDB_MODULE ?? 'my-nextjs-app'; | ||
|
|
||
| export function Providers({ children }: { children: React.ReactNode }) { | ||
| const connectionBuilder = useMemo(() => | ||
| DbConnection.builder() | ||
| .withUri(URI) | ||
| .withModuleName(MODULE), | ||
| [] | ||
| ); | ||
|
|
||
| return ( | ||
| <SpacetimeDBProvider connectionBuilder={connectionBuilder}> | ||
| {children} | ||
| </SpacetimeDBProvider> | ||
| ); | ||
| } | ||
| ``` | ||
| </StepCode> | ||
| </Step> | ||
|
|
||
| <Step title="Use React hooks for data"> | ||
| <StepText> | ||
| In your page components, use `useTable` to subscribe to table data and `useReducer` to call reducers. All components using these hooks must have the `"use client"` directive. | ||
| </StepText> | ||
| <StepCode> | ||
| ```tsx | ||
| // app/page.tsx | ||
| 'use client'; | ||
|
|
||
| import { tables, reducers } from '../src/module_bindings'; | ||
| import { useTable, useReducer } from 'spacetimedb/react'; | ||
|
|
||
| export default function Home() { | ||
| // Subscribe to table data - returns [rows, isLoading] | ||
| const [people] = useTable(tables.person); | ||
|
|
||
| // Get a function to call a reducer | ||
| const addPerson = useReducer(reducers.add); | ||
|
|
||
| const handleAdd = () => { | ||
| // Call reducer with object syntax | ||
| addPerson({ name: 'Alice' }); | ||
| }; | ||
|
|
||
| return ( | ||
| <ul> | ||
| {people.map((person, i) => <li key={i}>{person.name}</li>)} | ||
| </ul> | ||
| ); | ||
| } | ||
| ``` | ||
| </StepCode> | ||
| </Step> | ||
| </StepByStep> | ||
|
|
||
| ## Next steps | ||
|
|
||
| - See the [Chat App Tutorial](/tutorials/chat-app) for a complete example | ||
| - Read the [TypeScript SDK Reference](/sdks/typescript) for detailed API docs | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| { | ||
| "description": "Next.js App Router with TypeScript server", | ||
| "client_lang": "typescript", | ||
| "server_lang": "typescript" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| ../../licenses/apache2.txt |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| * { | ||
| box-sizing: border-box; | ||
| padding: 0; | ||
| margin: 0; | ||
| } | ||
|
|
||
| html, | ||
| body { | ||
| max-width: 100vw; | ||
| overflow-x: hidden; | ||
| } | ||
|
|
||
| body { | ||
| color: #333; | ||
| background: #fafafa; | ||
| } | ||
|
|
||
| a { | ||
| color: inherit; | ||
| text-decoration: none; | ||
| } | ||
|
|
||
| @media (prefers-color-scheme: dark) { | ||
| body { | ||
| color: #eee; | ||
| background: #111; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import type { Metadata } from 'next'; | ||
| import { Providers } from './providers'; | ||
| import './globals.css'; | ||
|
|
||
| export const metadata: Metadata = { | ||
| title: 'SpacetimeDB Next.js App', | ||
| description: 'A Next.js app powered by SpacetimeDB', | ||
| }; | ||
|
|
||
| export default function RootLayout({ | ||
| children, | ||
| }: { | ||
| children: React.ReactNode; | ||
| }) { | ||
| return ( | ||
| <html lang="en"> | ||
| <body> | ||
| <Providers>{children}</Providers> | ||
| </body> | ||
| </html> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| 'use client'; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't believe this should be necessary. |
||
|
|
||
| import { useState } from 'react'; | ||
| import { tables, reducers } from '../src/module_bindings'; | ||
| import { useSpacetimeDB, useTable, useReducer } from 'spacetimedb/react'; | ||
|
|
||
| export default function Home() { | ||
| const [name, setName] = useState(''); | ||
|
|
||
| const conn = useSpacetimeDB(); | ||
| const { isActive: connected } = conn; | ||
|
|
||
| // Subscribe to all people in the database | ||
| // useTable returns [rows, isLoading] tuple | ||
| const [people] = useTable(tables.person); | ||
|
|
||
| const addReducer = useReducer(reducers.add); | ||
|
|
||
| const addPerson = (e: React.FormEvent) => { | ||
| e.preventDefault(); | ||
| if (!name.trim() || !connected) return; | ||
|
|
||
| // Call the add reducer with object syntax | ||
| addReducer({ name: name }); | ||
| setName(''); | ||
| }; | ||
|
|
||
| return ( | ||
| <main style={{ padding: '2rem', fontFamily: 'system-ui, sans-serif' }}> | ||
| <h1>SpacetimeDB Next.js App</h1> | ||
|
|
||
| <div style={{ marginBottom: '1rem' }}> | ||
| Status:{' '} | ||
| <strong style={{ color: connected ? 'green' : 'red' }}> | ||
| {connected ? 'Connected' : 'Disconnected'} | ||
| </strong> | ||
| </div> | ||
|
|
||
| <form onSubmit={addPerson} style={{ marginBottom: '2rem' }}> | ||
| <input | ||
| type="text" | ||
| placeholder="Enter name" | ||
| value={name} | ||
| onChange={e => setName(e.target.value)} | ||
| style={{ padding: '0.5rem', marginRight: '0.5rem' }} | ||
| disabled={!connected} | ||
| /> | ||
| <button | ||
| type="submit" | ||
| style={{ padding: '0.5rem 1rem' }} | ||
| disabled={!connected} | ||
| > | ||
| Add Person | ||
| </button> | ||
| </form> | ||
|
|
||
| <div> | ||
| <h2>People ({people.length})</h2> | ||
| {people.length === 0 ? ( | ||
| <p>No people yet. Add someone above!</p> | ||
| ) : ( | ||
| <ul> | ||
| {people.map((person, index) => ( | ||
| <li key={index}>{person.name}</li> | ||
| ))} | ||
| </ul> | ||
| )} | ||
| </div> | ||
| </main> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| 'use client'; | ||
|
|
||
| import { useMemo } from 'react'; | ||
| import { SpacetimeDBProvider } from 'spacetimedb/react'; | ||
| import { DbConnection, ErrorContext } from '../src/module_bindings'; | ||
| import { Identity } from 'spacetimedb'; | ||
|
|
||
| const HOST = process.env.NEXT_PUBLIC_SPACETIMEDB_HOST ?? 'ws://localhost:3000'; | ||
| const DB_NAME = process.env.NEXT_PUBLIC_SPACETIMEDB_DB_NAME ?? 'nextjs-ts'; | ||
|
|
||
| const onConnect = (_conn: DbConnection, identity: Identity, token: string) => { | ||
| if (typeof window !== 'undefined') { | ||
| localStorage.setItem('auth_token', token); | ||
| } | ||
| console.log( | ||
| 'Connected to SpacetimeDB with identity:', | ||
| identity.toHexString() | ||
| ); | ||
| }; | ||
|
|
||
| const onDisconnect = () => { | ||
| console.log('Disconnected from SpacetimeDB'); | ||
| }; | ||
|
|
||
| const onConnectError = (_ctx: ErrorContext, err: Error) => { | ||
| console.log('Error connecting to SpacetimeDB:', err); | ||
| }; | ||
|
|
||
| export function Providers({ children }: { children: React.ReactNode }) { | ||
| const connectionBuilder = useMemo( | ||
| () => | ||
| DbConnection.builder() | ||
| .withUri(HOST) | ||
| .withModuleName(DB_NAME) | ||
| .withToken( | ||
| typeof window !== 'undefined' | ||
| ? localStorage.getItem('auth_token') || undefined | ||
| : undefined | ||
| ) | ||
| .onConnect(onConnect) | ||
| .onDisconnect(onDisconnect) | ||
| .onConnectError(onConnectError), | ||
| [] | ||
| ); | ||
|
|
||
| return ( | ||
| <SpacetimeDBProvider connectionBuilder={connectionBuilder}> | ||
| {children} | ||
| </SpacetimeDBProvider> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import type { NextConfig } from 'next'; | ||
|
|
||
| const nextConfig: NextConfig = { | ||
| // Next.js configuration | ||
| // Note: Use port 3001 (via npm scripts) to avoid conflict with SpacetimeDB on port 3000 | ||
| }; | ||
|
|
||
| export default nextConfig; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should run on 3000. The quickstart should be connecting to Maincloud, not the local server.
Yours might be if you have your default set to local in the spacetime CLI.