Skip to content

Feat(example): Add nextjs-supabase-realtime-task example #71

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions nextjs-supabase/.env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
39 changes: 39 additions & 0 deletions nextjs-supabase/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
54 changes: 54 additions & 0 deletions nextjs-supabase/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
## nextjs-supabase-realtime-task example

A full-stack collaborative solution demonstrating real-time synchronization using Next.js, powered by Legend-State for granular state management and Supabase for backend services. Core capabilities include:

- Real-time bidirectional synchronization: Instant updates with millisecond latency via Supabase Realtime
- Automatic timestamp tracking: Built-in creation and modification time recording
- End-to-end type safety: Strict TypeScript definitions across database models
- Optimized reactivity: Efficient state updates through Legend-State's observable system

---

## Setup

Create `.env.local`

```bash
cp .env.local.example .env.local
```

Link Supabase

```bash
supabase link
```

Apply Database

```bash
supabase db push

```

## Run

Install

```bash
pnpm install
```

Start

```bash
pnpm run dev
```

## Types

Generate `types.ts`

```bash
supabase start
supabase gen types --lang=typescript --local > src/lib/types.ts
```
12 changes: 12 additions & 0 deletions nextjs-supabase/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
@import "tailwindcss";

:root {
--background: #171717;
--foreground: #ffffff;
}

@theme inline {
--color-mobai-background: var(--background);
--color-mobai-foreground: var(--foreground);
--ease-mobai-bounce: cubic-bezier(0.84, 0, 0.165, 1);
}
13 changes: 13 additions & 0 deletions nextjs-supabase/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import "./globals.css";

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html>
<body className={`antialiased bg-mobai-background`}>{children}</body>
</html>
);
}
27 changes: 27 additions & 0 deletions nextjs-supabase/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"use client";

import { observer } from "@legendapp/state/react";
import NewTask from "@/components/NewTask";
import TaskList from "@/components/TaskList";

const Home = observer(() => {
return (
<>
<div className="fixed top-0 left-0 w-full pointer-events-none">
<h1 className="p-4 text-2xl whitespace-nowrap sm:text-6xl md:text-7xl font-mono lg:text-8xl xl:text-9xl transition-all duration-500 ease-mobai-bounce text-mobai-foreground font-bold sm:rotate-90 origin-bottom-left">
Task Demo
</h1>
</div>
<div className="pt-10 sm:pt-4 transition-all duration-500 ease-mobai-bounce w-full">
<div className="max-w-xl lg:max-w-2xl transition-all duration-500 ease-mobai-bounce mx-auto p-4">
<div>
<NewTask />
<TaskList />
</div>
</div>
</div>
</>
);
});

export default Home;
28 changes: 28 additions & 0 deletions nextjs-supabase/components/NewTask.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"use client";

import { addTask } from "../lib/store";
import React, { useState } from "react";

const NewTask = () => {
const [text, setText] = useState("");
const handleSubmitEditing = () => {
setText("");
addTask(text);
};
return (
<div>
<input
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleSubmitEditing();
}
}}
className="text-mobai-foreground border-mobai-foreground border-2 transition-all duration-500 ease-mobai-bounce font-bold w-full outline-none p-3 sm:p-4 hover:bg-mobai-foreground hover:text-mobai-background"
/>
</div>
);
};

export default NewTask;
29 changes: 29 additions & 0 deletions nextjs-supabase/components/TaskItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Check from "@/components/icons/Check";
import Circle from "@/components/icons/Circle";
import { Tables } from "../types/store.types";
import { toggleDone } from "../lib/store";

const TaskItem = ({ task }: { task: Tables<"tasks"> }) => {
const handlePress = () => {
toggleDone(task.id);
};
return (
<li className="bg-mobai-foreground p-3 sm:p-4 transition-all duration-500 ease-mobai-bounce">
<button
onClick={handlePress}
className="flex flex-row justify-between w-full items-center"
>
<p className="text-mobai-background font-bold">{task.text}</p>
<p>
{task.done ? (
<Check className="size-6" />
) : (
<Circle className="size-6" />
)}
</p>
</button>
</li>
);
};

export default TaskItem;
30 changes: 30 additions & 0 deletions nextjs-supabase/components/TaskList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"use client";

import { tasks$ } from "../lib/store";
import { Tables } from "../types/store.types";
import TaskItem from "@/components/TaskItem";
import { useEffect, useState } from "react";
import { observer } from "@legendapp/state/react";

const TaskList = observer(() => {
const [isClient, setIsClient] = useState(false);
const tasks = tasks$.get();
const taskArray = Object.values(tasks || {}).reverse();

useEffect(() => {
setIsClient(true);
}, []);

return (
isClient &&
tasks && (
<ul className="flex flex-col gap-4 py-4">
{taskArray.map((task: Tables<"tasks">) => (
<TaskItem key={task.id} task={task} />
))}
</ul>
)
);
});

export default TaskList;
22 changes: 22 additions & 0 deletions nextjs-supabase/components/icons/Check.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { IconProps } from "@/types/icon.types";

const Check: React.FC<IconProps> = ({ className }) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={`lucide lucide-check ${className}`}
>
<path d="M20 6 9 17l-5-5" />
</svg>
);
};

export default Check;
22 changes: 22 additions & 0 deletions nextjs-supabase/components/icons/Circle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { IconProps } from "@/types/icon.types";

const Circle: React.FC<IconProps> = ({ className }) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={`lucide lucide-circle ${className}`}
>
<circle cx="12" cy="12" r="10" />
</svg>
);
};

export default Circle;
16 changes: 16 additions & 0 deletions nextjs-supabase/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
baseDirectory: __dirname,
});

const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];

export default eslintConfig;
57 changes: 57 additions & 0 deletions nextjs-supabase/lib/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { createClient } from "@supabase/supabase-js";
import { configureSynced } from "@legendapp/state/sync";
import { observable } from "@legendapp/state";
import { ObservablePersistLocalStorage } from "@legendapp/state/persist-plugins/local-storage";
import { syncedSupabase } from "@legendapp/state/sync-plugins/supabase";
import { v4 as uuidv4 } from "uuid";

import { Database } from "../types/store.types";

const supabase = createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);

const generateId = () => uuidv4();

const customSynced = configureSynced(syncedSupabase, {
persist: {
plugin: ObservablePersistLocalStorage,
},
generateId,
supabase,
changesSince: "last-sync",
fieldCreatedAt: "created_at",
fieldUpdatedAt: "updated_at",
fieldDeleted: "deleted",
});

export const tasks$ = observable(
customSynced({
supabase,
collection: "tasks",
select: (from) =>
from.select("id,counter,text,done,created_at,updated_at,deleted"),
actions: ["read", "create", "update", "delete"],
realtime: true,
persist: {
name: "tasks",
retrySync: true,
},
retry: {
infinite: true,
},
})
);

export const addTask = (text: string) => {
const id = generateId();
tasks$[id].assign({
id,
text,
});
};

export const toggleDone = (id: string) => {
tasks$[id].done.set((prev) => !prev);
};
7 changes: 7 additions & 0 deletions nextjs-supabase/next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
/* config options here */
};

export default nextConfig;
Loading