惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
Webroot Blog
Webroot Blog
T
The Blog of Author Tim Ferriss
S
Schneier on Security
罗磊的独立博客
P
Privacy & Cybersecurity Law Blog
阮一峰的网络日志
阮一峰的网络日志
F
Fortinet All Blogs
P
Palo Alto Networks Blog
月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
量子位
NISL@THU
NISL@THU
C
CERT Recently Published Vulnerability Notes
Cisco Talos Blog
Cisco Talos Blog
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
Lohrmann on Cybersecurity
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
L
LINUX DO - 热门话题
Help Net Security
Help Net Security
B
Blog RSS Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
I
InfoQ
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Cloudflare Blog
H
Heimdal Security Blog
Last Week in AI
Last Week in AI
美团技术团队
云风的 BLOG
云风的 BLOG
C
Check Point Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
V
Visual Studio Blog
G
GRAHAM CLULEY
AI
AI
Security Latest
Security Latest
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
雷峰网
雷峰网
Cyberwarzone
Cyberwarzone
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Superhuman-Style Collaborative Email Editor with Next.js and Velt🔥
Astrodevil · 2026-05-22 · via DEV Community

Introduction

Superhuman rethinks email as a fast, focused workspace. Its clean interface and keyboard-first flow make working through email feel deliberate instead of noisy.

Adding collaboration to this kind of experience is where things get difficult. Real-time updates, user presence, inline comments, and notifications usually require complex backend systems and real-time infrastructure.

In this tutorial, we’ll build a Superhuman-style collaborative email interface using Next.js and Velt. The UI stays simple and frontend-focused, while Velt handles comments, presence, and notifications behind the scenes.

App UI

What We’re Building

  • A Superhuman-style email interface with a clean inbox and focused email preview
  • Inline comments directly on email content using Velt
  • Real-time user presence when multiple users view the same email
  • In-app notifications for collaboration activity
  • Light and dark theme support
  • Multi-user collaboration using predefined users, without backend or database setup

Tech Stack Overview

  • Next.js (App Router): Structures the application and layouts for a modern email interface
  • React: Builds the inbox, email preview, and interactive UI components
  • Tailwind CSS: Enables a clean, minimal UI with easy theming
  • shadcn ui (powered by Radix UI): Provides accessible, reusable UI primitives
  • Tiptap: Renders rich email content and supports inline annotations
  • Zustand: Manages demo users for multi-user collaboration testing
  • Velt: Acts as the collaboration layer, adding comments, presence, and notifications without backend infrastructure

Project Setup

Start by cloning the repository and moving into the project directory:

gitclone https://github.com/Studio1HQ/superhuman-demo-eg
cd superhuman-demo-eg

Enter fullscreen mode Exit fullscreen mode

Next, install the project dependencies:

npm install

Enter fullscreen mode Exit fullscreen mode

To enable collaboration features, create a .env.local file in the root of the project and add your Velt API key:

NEXT_PUBLIC_VELT_ID=your_velt_api_key_here

Enter fullscreen mode Exit fullscreen mode

You can generate this key from the Velt dashboard. Once the environment variable is set, start the development server:

npm run dev

Enter fullscreen mode Exit fullscreen mode

Open http://localhost:3000 in your browser to see the Superhuman-style email interface running locally with real-time collaboration enabled.

UI of editor

Why Use Velt?

If you try to add collaboration yourself, you quickly run into hard problems. You need real-time updates, user presence, comments that stay in sync, and notifications that fire at the right moment. That usually means WebSockets, backend services, and a lot of edge cases to manage as more users join.

Velt lets you skip all of that. You plug it into your app and get comments, presence, notifications, and shared context immediately. You don’t worry about syncing users or handling concurrent updates. Your code stays focused on the UI and user experience, not real-time infrastructure.

This is especially useful when you’re building fast. You can take an existing interface like an email preview or document view and make it collaborative in minutes. Features like reactions, read status, and threaded comments work out of the box, so you spend time improving the product instead of rebuilding collaboration from scratch.

Velt landing page

Understanding the App Structure

This project follows a clean, layout-first structure using the Next.js App Router. Routing and global configuration live inside the app/ directory, while the main application UI is grouped under the (app) route for clarity.

Global styles and shared providers are defined at the layout level. This ensures theme handling and collaboration setup are available across the entire app without passing props through components.

The UI is built in a component-driven way. Core features like the sidebar, email list, and email preview live in the components folder, while reusable UI primitives are isolated in components/ui. This separation keeps the codebase easy to navigate and ready for collaboration features.

Building the Email UI

Before adding real-time collaboration, the first step is getting the email experience right. This section focuses purely on structure and interaction, keeping the UI fast and familiar, inspired by Superhuman.

Sidebar and Navigation

  • components/sidebar.tsx
  • components/top-navigation.tsx

The sidebar is responsible for inbox navigation. It provides quick access to different sections and keeps the layout consistent, which is important for an email workflow where users switch context frequently.

The top navigation handles global actions such as search, theme toggling, and user context. At this stage, it serves purely as a layout and control surface, without any collaboration-related logic.

export function Sidebar({ isOpen, onClose }: SidebarProps) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

Enter fullscreen mode Exit fullscreen mode

Email List and Preview

  • components/email-list.tsx
  • components/email-preview.tsx

The email list displays available messages and manages selection. When a user selects an email, the selected data is passed down to the preview component, keeping state flow simple and predictable.

The email preview renders the full content of the selected message. This component is intentionally kept focused on reading and layout, making it a clean and stable foundation before introducing collaborative features later in the app.

export function EmailPreview() {
    return (
        <div className="flex-1 flex bg-background min-w-0 hidden lg:flex">
            {/* Main Email Content */}
            <div className="flex-1 flex flex-col">
                {/* Email Header */}
                <div className="border-b p-6">
                    <div className="flex items-start justify-between mb-4">
                        <div className="flex-1">
                            <h1 className="text-xl font-semibold mb-2">
                                {currentEmail.subject}
                            </h1>
                            <div className="flex items-center gap-4 text-sm text-muted-foreground">
                                <div className="flex items-center gap-2">
                                    <Avatar className="w-6 h-6">
                                        <AvatarImage src={currentEmail.senderAvatar} />
                                        <AvatarFallback className="text-xs">
                                            {currentEmail.sender.charAt(0)}
                                        </AvatarFallback>
                                    </Avatar>
                                    <span className="text-[13px] font-medium text-foreground">{currentEmail.sender}</span>
                                    <span className="text-[13px] hidden md:inline">&lt;{currentEmail.senderEmail}&gt;</span>
                                </div>
                                <span className="text-[13px] hidden sm:inline">{format(currentEmail.date, 'MMM d, yyyy')}</span>
                                <span className="text-[13px] sm:hidden">{format(currentEmail.date, 'MMM d, yyyy')}</span>
                            </div>
                        </div>

                        <div className="flex items-center gap-1">
                            <Button variant="ghost" size="icon">
                                <Star className={currentEmail.isStarred ? "fill-yellow-400 text-yellow-400" : ""} />
                            </Button>
                            <Button variant="ghost" size="icon">
                                <Archive className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="icon">
                                <Trash2 className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="icon" className="hidden sm:flex">
                                <MoreHorizontal className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>

                    {/* Labels */}
                    <div className="flex gap-2">
                        {currentEmail.labels.map((label) => (
                            <Badge key={label} variant="secondary" className="text-xs">
                                {label}
                            </Badge>
                        ))}
                    </div>
                </div>

                {/* Email Content */}
                <div className="flex-1 p-6 overflow-y-auto max-h-[calc(100vh-330px)]">
                    <EmailPreviewComponent content={currentEmail.content} />
                </div>

                {/* Action Bar */}
                <div className="border-t p-4">
                    <div className="flex items-center gap-2">
                        <Button className="gap-2">
                            <Reply className="h-4 w-4" />
                            <span className="hidden sm:inline">Reply</span>
                        </Button>
                        <Button variant="outline" className="gap-2">
                            <ReplyAll className="h-4 w-4" />
                            <span className="hidden md:inline">Reply All</span>
                        </Button>
                        <Button variant="outline" className="gap-2">
                            <Forward className="h-4 w-4" />
                            <span className="hidden sm:inline">Forward</span>
                        </Button>
                    </div>
                </div>

                {/* Keyboard Shortcuts Helper */}
                <div className="border-t bg-muted/20 p-3 hidden md:block">
                    <div className="flex items-center justify-center gap-6 text-xs text-muted-foreground">
                        <div className="flex items-center gap-1">
                            <kbd className="px-1.5 py-0.5 bg-muted rounded text-xs">r</kbd>
                            <span>Reply</span>
                        </div>
                        <div className="flex items-center gap-1">
                            <kbd className="px-1.5 py-0.5 bg-muted rounded text-xs">a</kbd>
                            <span>Archive</span>
                        </div>
                        <div className="flex items-center gap-1">
                            <kbd className="px-1.5 py-0.5 bg-muted rounded text-xs">s</kbd>
                            <span>Star</span>
                        </div>
                        <div className="flex items-center gap-1">
                            <kbd className="px-1.5 py-0.5 bg-muted rounded text-xs">#</kbd>
                            <span>Delete</span>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    );
}

Enter fullscreen mode Exit fullscreen mode

Reusable UI Components

All reusable UI components live inside the components/ui folder. These components handle common interface patterns such as buttons, inputs, avatars, dropdown menus, and modals that are used across the inbox and email preview.

Instead of building these elements from scratch, the project uses shadcn ui, which is built on top of Radix UI primitives. Radix provides accessibility, keyboard interactions, and predictable behavior, while shadcn ui keeps the components unstyled and flexible so they fit naturally into the design.

This approach keeps the UI consistent across the app. Updating a button, input, or dropdown in one place automatically reflects everywhere it’s used, making the interface easier to maintain as the application grows.

User Management for Collaboration Testing

Next, the app needs a way to represent different users so collaboration can be tested locally. Instead of setting up full authentication, this project uses a simple user store defined in helper/userdb.ts.

The file contains a small set of predefined users with names and avatars. This makes it easy to switch between users and simulate real collaboration scenarios without signing in or managing sessions. When a user is changed, the app updates instantly, which is enough to test presence, comments, and notifications.

For this tutorial, this approach replaces a full authentication system. In a production app, these users would come from your real auth flow, but for learning and experimentation, a lightweight user store keeps the focus on collaboration rather than authentication complexity.

The userdb.ts file look like this:

import { create } from "zustand";
import { persist } from "zustand/middleware";

export type User = {
  uid: string;
  displayName: string;
  email: string;
  photoUrl?: string;
};

export interface UserStore {
  user: User | null;
  setUser: (user: User) => void;
}

export const userIds = ["user001", "user002"];
export const names = ["Nany", "Mary"];

export const useUserStore = create<UserStore>()(
  persist(
    (set) => ({
      user: null,
      setUser: (user) => set({ user }),
    }),
    {
      name: "user-storage",
    }
  )
);

Enter fullscreen mode Exit fullscreen mode

Theme Management

The app includes light and dark theme support using a custom hook defined in hooks/use-theme.tsx. The hook controls the active theme and updates the document state so the UI responds immediately to theme changes.

The selected theme is stored in localStorage, which allows the preference to persist across page reloads and browser sessions. Users return to the same theme without needing to reset it each time.

This theme state is also passed to Velt components. As a result, comments, presence indicators, and notification panels automatically match the app’s light or dark mode, keeping the experience visually consistent.

Introducing Velt into the App

With the email UI in place, the next step is to introduce real-time collaboration. Velt works by wrapping your application with a provider and then identifying who the current user is and what they are collaborating on. Once this is set up, all collaboration features are built on top of it.

Adding the Velt Provider

app/(app)/layout.tsx

The first step is to wrap the application with the VeltProvider. This initializes Velt and makes the collaboration client available throughout the app. Without this provider, features like comments, presence, and notifications will not work.

Add the provider at the layout level, so it applies to every page:

"use client";

import { ThemeProvider } from "@/hooks/use-theme";
import { VeltProvider } from "@veltdev/react";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <VeltProvider apiKey={process.env.NEXT_PUBLIC_VELT_ID || ""}>
      <ThemeProvider>{children}</ThemeProvider>
    </VeltProvider>
  );
}

Enter fullscreen mode Exit fullscreen mode

Adding Collaboration Controls to the Header

components/top-navigation.tsx

The header is the right place for collaboration controls because it’s always visible and shared across the app. It provides global context, showing who is online and surfacing collaboration activity without interrupting the email content.

Velt’s UI components are added directly to the header:

  • VeltPresence
  • VeltNotificationsTool
  • VeltCommentsSidebar
  • VeltSidebarButton

Once added, these components work automatically with the existing user and document setup, enabling real-time collaboration across the app.

"use client";

import { Search, Command, Menu } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  useVeltClient,
  VeltCommentsSidebar,
  VeltNotificationsTool,
  VeltPresence,
  VeltSidebarButton,
} from "@veltdev/react";

import { names, userIds, useUserStore } from "@/helper/userdb";
import { User } from "lucide-react";
import React, { useEffect, useMemo, useRef } from "react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { ChevronDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import useTheme, { ThemeToggleButton } from "@/hooks/use-theme";

Enter fullscreen mode Exit fullscreen mode

Next, let us see how the Velt components are used.

The VeltPresence component displays avatars of users who are currently viewing the same document. It updates automatically as users join or leave, giving immediate awareness of who is active.

VeltNotificationsTool adds a notification bell that surfaces collaboration events such as replies, mentions, and comment activity. Notifications are grouped and updated in real time, without requiring any custom event handling.

VeltSidebarButton and VeltCommentsSidebar work together to manage discussions. The button toggles the comments sidebar, while the sidebar itself provides a centralized view of all comments across the document. Both components stay in sync with the current user and document context automatically.

Together, these components add presence, notifications, and discussion management to the app with minimal code, relying entirely on the existing Velt setup for user identification and document context.

<div className="flex items-center gap-1">
          <div className="flex items-center space-x-3">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  className="flex items-center space-x-2 h-8 bg-white  text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-200  dark:border dark:border-white/30 dark:!bg-[#121212] dark:hover:!bg-gray-700"
                >
                  <Avatar className="w-5 h-5">
                    <AvatarImage
                      src={user?.photoUrl || "https://via.placeholder.com/100"}
                      alt={user?.displayName || "User"}
                    />
                    <AvatarFallback className="text-xs">
                      {user?.displayName}
                    </AvatarFallback>
                  </Avatar>
                  <span className="text-sm truncate max-w-[100px]">
                    {user?.displayName}
                  </span>
                  <ChevronDown size={14} />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="end"
                className="w-64 bg-white  text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-200  dark:bg-[#121212] dark:border dark:border-white/30"
              >
                <DropdownMenuLabel>Select User</DropdownMenuLabel>
                <DropdownMenuSeparator className="dark:bg-white/40" />
                {predefinedUsers.map((Currentuser) => (
                  <DropdownMenuItem
                    key={Currentuser.uid}
                    onClick={() => setUser(Currentuser)}
                    className="flex items-center space-x-3 p-3 cursor-pointer hover:!bg-gray-100 hover:dark:!bg-[#121212] dark:hover:!bg-gray-700"
                  >
                    <Avatar className="w-8 h-8">
                      <AvatarImage
                        src={Currentuser.photoUrl}
                        alt={Currentuser.displayName}
                      />
                      <AvatarFallback className="text-xs">
                        {Currentuser.displayName}
                      </AvatarFallback>
                    </Avatar>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-gray-900 dark:text-white/70">
                        {Currentuser.displayName}
                      </div>
                      <div className="text-xs text-gray-500 dark:text-white/60">
                        {Currentuser.email}
                      </div>
                      <div className="text-xs text-gray-400 dark:text-white/50">
                        User
                      </div>
                    </div>
                    {user?.uid === Currentuser.uid && (
                      <div className="w-2 h-2 bg-blue-600 rounded-full" />
                    )}
                  </DropdownMenuItem>
                ))}
                <DropdownMenuSeparator />
                <DropdownMenuItem className="flex items-center space-x-2 text-blue-600 hover:dark:bg-[#515881] ">
                  <User size={16} />
                  <span className="hover:dark:text-white/70">Manage Users</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
            <div className="max-md:hidden">
              <VeltPresence />
            </div>
            <VeltNotificationsTool darkMode={theme === "dark"} />
          </div>
          <VeltSidebarButton darkMode={theme === "dark"} />
          <VeltCommentsSidebar />

          <ThemeToggleButton />
        </div>
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Identifying Users and Documents

components/top-navigation.tsx

Once the provider is in place, Velt needs to know two things: who the current user is and which document they are collaborating on. This is handled using the Velt client.

When a user is selected from the demo user store, the app identifies them with Velt using client.identify(). At the same time, a document context is set using client.setDocuments(). This document acts as the shared collaboration space.

Here’s the core logic that connects users and documents to Velt:

// Handle Velt client initialization, user identification, and document setting
  useEffect(() => {
    if (!client || !user || isInitializingRef.current) {
      console.log("Velt init skipped:", {
        client: !!client,
        user: !!user,
        initializing: isInitializingRef.current,
      });
      return;
    }

    const initializeVelt = async () => {
      isInitializingRef.current = true;
      try {
        // Detect user switch
        const isUserSwitch = prevUserRef.current?.uid !== user.uid;
        prevUserRef.current = user;

        console.log("Starting Velt init for user:", user.uid, { isUserSwitch });

        // Re-identify the user (handles initial and switches)
        const veltUser = {
          userId: user.uid,
          organizationId: "organization_id",
          name: user.displayName,
          email: user.email,
          photoUrl: user.photoUrl,
        };
        await client.identify(veltUser);
        console.log("Velt user identified:", veltUser.userId);
        await client.setDocuments([
          {
            id: "superhuman-velt",
            metadata: { documentName: "superhuman-velt" },
          },
        ]);
        console.log("Velt documents set: superhuman-velt");
      } catch (error) {
        console.error("Error initializing Velt:", error);
      } finally {
        isInitializingRef.current = false;
      }
    };

Enter fullscreen mode Exit fullscreen mode

Inline comments are implemented at the content level inside the email preview. Presence and notifications are handled separately in the header, where a global collaboration context makes more sense.

EmailPreviewComponent.tsx

Using Velt, the email preview component structure looks like this:

"use client";

import { useEditor, EditorContent, BubbleMenu } from "@tiptap/react";
import {
  TiptapVeltComments,
  renderComments,
  addComment,
} from "@veltdev/tiptap-velt-comments";
import { useCommentAnnotations } from "@veltdev/react";
import { useEffect } from "react";
import { StarterKit } from "@tiptap/starter-kit";
import { Button } from "./button";

import { MessageCircle } from "lucide-react";

const EDITOR_ID = "superhuman-demo-email";

const EmailPreviewComponent = ({content=`<p>Data for custom</p>`}:{content?: string}) => {
  // Initialize Tiptap editor
  const editor = useEditor({
    extensions: [
      TiptapVeltComments.configure({
        persistVeltMarks: false,
      }),
      StarterKit,
    ],
    content,
    autofocus: true,
    immediatelyRender: false,
  });

  // Get annotations
  const annotations = useCommentAnnotations();

  // Render annotations when editor and annotations are both ready
  useEffect(() => {
    if (editor && annotations?.length) {
      renderComments({
        editor,
        editorId: EDITOR_ID,
        commentAnnotations: annotations,
      });
    }
  }, [editor, annotations]);

  // Add comment handler - stop propagation to prevent parent elements from capturing events
  const onClickComments = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (editor) {
      addComment({
        editor,
        editorId: EDITOR_ID,
      });
    }
  };

Enter fullscreen mode Exit fullscreen mode

Running and Testing the App

Start the development server by running:

npm run dev

Enter fullscreen mode Exit fullscreen mode

Once the app is running, open http://localhost:3000 in your browser. To test collaboration, open the same URL in two different browser windows or profiles.

Video Demo

Things to Consider Before Production

Before shipping to production, replace the demo user store with your real authentication system so users are identified securely. Use dynamic document IDs instead of a hardcoded value to scope collaboration to individual emails or threads.

Configure permissions and access control to manage who can view, comment, or interact with content. Finally, add proper error handling and monitor collaboration performance as usage scales.

Demo

Check here: https://superhuman-mail-velt.vercel.app/

When exploring the demo, open it in two browser windows, switch between different users, select the same email, and try adding comments to see presence, notifications, and real-time updates in action.

Conclusion

You’ve built a Superhuman-style email interface with real-time collaboration, including inline comments, user presence, and in-app notifications. More importantly, you did this without building or maintaining any custom backend or real-time infrastructure.

Velt handles the heavy lifting behind the scenes, so your code stays focused on the user experience instead of synchronization, events, and edge cases. This makes it much easier to add collaboration to content-driven apps like email, documents, or dashboards.

If you’re building your own SaaS product or internal tool, you can take this further by adding more Velt features such as reactions, read status, mentions, and threaded discussions. These features plug into the same setup and work out of the box.

To explore what else you can build, check out Velt and start adding real-time collaboration to your app without reinventing the backend.

Resources