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

推荐订阅源

A
Arctic Wolf
有赞技术团队
有赞技术团队
H
Help Net Security
N
Netflix TechBlog - Medium
G
Google Developers Blog
GbyAI
GbyAI
Jina AI
Jina AI
D
DataBreaches.Net
博客园 - Franky
Recent Announcements
Recent Announcements
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
N
News | PayPal Newsroom
S
SegmentFault 最新的问题
B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
S
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
V
V2EX
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 【当耐特】
P
Privacy International News Feed
T
The Exploit Database - CXSecurity.com
云风的 BLOG
云风的 BLOG
F
Full Disclosure
Microsoft Security Blog
Microsoft Security Blog
MongoDB | Blog
MongoDB | Blog
V
Vulnerabilities – Threatpost
C
CERT Recently Published Vulnerability Notes
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
罗磊的独立博客
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
O
OpenAI News
P
Palo Alto Networks Blog
The Cloudflare Blog
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tenable Blog
雷峰网
雷峰网
C
Cisco Blogs

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
EasyPollVote [Dev Log #4]
FrancisTRᴅᴇᴠ · 2026-05-01 · via DEV Community

Welcome to the Forth DEV LOG!

Welcome to the forth Dev Log of my full stack application called EasyPollVote (EasyPV)!


What is EasyPollVote (EasyPV)?

A Next.js application where the ultimate goal is having the convenience to create your own poll and share it for others to vote on your custom poll!

For example, a user can create their own poll. Their poll can be something like "Do you like Cats or Dogs?" following the two options users can vote on "Cats" or "Dogs". Then, they will be able to send the private link to anyone and the voters can vote on it without the need to create an account!

That is the whole goal. Do note that this goal may change as time goes on!

The current goal is to learn about the use of Supabase!


Current Progress

Nothing new other than cleaning up code. @sylwia-lask made a poll and here are the results!

As mention in the last Dev Log, I will now be discussing how the Custom Polls work!

Part 1

Here is the HTML code based on the image above:

<form onSubmit={handleSubmit} className="w-full p-4 sm:p-6 md:p-8">
    <h2 className="text-xl font-semibold text-center p-4 sm:p-5 border-4 border-indigo-200 border-b-indigo-500">
        Create a Poll
    </h2>

    <div className="mt-5 mb-5 justify-center">
        {/* TITLE */}
        <label>
            <h1>Poll Title</h1>

            <input
                type="text"
                placeholder="Poll Title (required)"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full mb-4 p-3 border"
                required
            />
        </label>

        <label>
            <h1>Poll End Date</h1>

            {/* END DATE */}
            <input
                type="datetime-local"
                value={endDate}
                onChange={(e) =>
                    handleEndDateChange(e.target.value)
                }
                className={`w-full mb-1 p-3 border ${endDateError ? "border-red-500" : ""
                    }`}
                required
            />
        </label>

        {/* ERROR */}
        {endDateError && (
            <p className="text-red-500 text-sm mb-3">
                {endDateError}
            </p>
        )}
    </div>

    {/* OPTIONS */}
    <label className="block mb-2 font-medium">
        Poll Options
    </label>

    <div className="w-full mb-4 p-4 sm:p-6 border">
        {options.map((opt, index) => (
            <div
                key={index}
                className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 mb-3"
            >
                <input
                    type="text"
                    placeholder={`Option ${index + 1}`}
                    value={opt.text}
                    onChange={(e) =>
                        handleOptionChange(
                            index,
                            e.target.value
                        )
                    }
                    className="flex-1 p-3 border"
                    required={index < 2}
                />

                <div className="flex gap-2">
                    <input
                        type="color"
                        value={opt.color}
                        onChange={(e) =>
                            handleColorChange(
                                index,
                                e.target.value
                            )
                        }
                        className="w-12 h-12 p-1 border cursor-pointer"
                    />

                    {index >= 2 && (
                        <button
                            type="button"
                            onClick={() =>
                                removeOption(index)
                            }
                            className="px-3 py-3 bg-red-500 text-white"
                        ></button>
                    )}
                </div>
            </div>
        ))}

        {options.length < 4 && (
            <button
                type="button"
                onClick={addOption}
                className="w-full mb-2 p-3 border"
            >
                + Add Option
            </button>
        )}
    </div>

    {/* SUBMIT */}
    <button
        type="submit"
        disabled={loading || !!endDateError}
        className="w-full bg-blue-500 text-white py-3 disabled:bg-gray-400"
    >
        {loading ? "Submitting..." : "Submit"}
    </button>

    {message && (
        <p className="text-sm text-center mt-3">
            {message}
        </p>
    )}
</form>

Enter fullscreen mode Exit fullscreen mode

In this form, we have the main functionalities:

  • "handleSubmit"
  • "setTitle"
  • "handleEndDateChange"
  • "handleOptionChange" and "handleColorChange"
  • "addOption" and "removeOption"

I will be discussing in reverse order.

"addOption" and "removeOption"

Nothing big is going on. Basically, the user have the option to create up to 4 options for the voter to vote on and being able to delete the options as well:

// Add/Remove options (max 4, min 2)
const addOption = () => {
    if (options.length < 4) {
        setOptions([...options, { text: "", color: "#a855f7" }]); // Add option
    }
};
const removeOption = (index: number) => {
    if (options.length <= 2) return;
    setOptions(options.filter((_, i) => i !== index)); // Remove option
};

Enter fullscreen mode Exit fullscreen mode

"handleOptionChange" and "handleColorChange"

Speaking of options, you have the ability to enter a name for that option and the color associate with it.

// Poll options w/ color associated with each option
const handleOptionChange = (index: number, value: string) => {
    const updated = [...options];
    updated[index].text = value;
    setOptions(updated);
};
const handleColorChange = (index: number, color: string) => {
    const updated = [...options];
    updated[index].color = color;
    setOptions(updated);
};

Enter fullscreen mode Exit fullscreen mode

"handleEndDateChange"

Based on the input, it get stored:

const handleEndDateChange = (value: string) => {
    setEndDate(value);
    setEndDateError(validateEndDate(value)); // Validate the date
};

Enter fullscreen mode Exit fullscreen mode

"setTitle"

Just storing in a variable :)

"handleSubmit"

I save the biggest one for last!

// Handling submit of the form
const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage("");


    const filteredOptions = options.filter(
        (opt) => opt.text.trim() !== ""
    );

    try {
        // duplicate check uses filtered options only
        for (let i = 0; i < filteredOptions.length; i++) {
            for (let j = i + 1; j < filteredOptions.length; j++) {
                if (filteredOptions[i].text.trim().toLowerCase() === filteredOptions[j].text.trim().toLowerCase()) {
                    setMessage("Options cannot be identical!");
                    setLoading(false);
                    return;
                }
            }
        }

        const isoEndDate = new Date(endDate).toISOString();

        // POST request one all the validation is complete
        const res = await fetch("/api/poll", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                title,
                options: filteredOptions,
                endDate: isoEndDate,
            }),
        });

        const data = await res.json();

        if (!res.ok) {
            throw new Error(data.error || "Something went wrong");
        }

        const pollUrl = `${window.location.origin}/poll/${data.pollId}`;

        setMessage(
            "Poll created successfully! Share this link: " + pollUrl
        );

        // reset form
        setTitle("");
        setEndDate("");
        setEndDateError("");
        setOptions([
            { text: "", color: "#22c55e" },
            { text: "", color: "#3b82f6" },
        ]);
    } catch (err: any) {
        setMessage(err.message);
    } finally {
        setLoading(false);
    }
};

Enter fullscreen mode Exit fullscreen mode

The first big thing it it does is ensuring there are no duplicate values in the options section. If there are no duplicate names, we then proceed to set the date to an ISO and do a POST request on api/poll.

// POST request one all the validation is complete
const res = await fetch("/api/poll", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        title,
        options: filteredOptions,
        endDate: isoEndDate,
    }),
});

Enter fullscreen mode Exit fullscreen mode

It uploads the title, options, and its enddate of the poll.

Once the user submits the form, it generates a link for the user to share with others to vote on their poll!

const pollUrl = `${window.location.origin}/poll/${data.pollId}`;

setMessage(
    "Poll created successfully! Share this link: " + pollUrl
);

Enter fullscreen mode Exit fullscreen mode

In the api/poll/route.ts, it only has a single POST request:

export async function POST(req: Request) {
    try {
        const body = await req.json();

        const { title, options, endDate } = body;

        // 1. Validate input
        if (!title || !endDate || !options || options.length < 2) {
            return NextResponse.json(
                { error: "Invalid input" },
                { status: 400 }
            );
        }

        // 2. Validate ISO date (already normalized from client)
        const normalizedEndDate = new Date(endDate);

        if (isNaN(normalizedEndDate.getTime())) {
            return NextResponse.json(
                { error: "Invalid date format" },
                { status: 400 }
            );
        }

        if (normalizedEndDate.getTime() <= Date.now()) {
            return NextResponse.json(
                { error: "End date must be in the future" },
                { status: 400 }
            );
        }

        // 3. Insert Poll
        const { data: pollData, error: pollError } = await supabase
            .from("Poll")
            .insert([
                {
                    PollTitle: title,
                    Poll_EndDate: endDate,
                    Poll_Ended: false,
                },
            ])
            .select()
            .single();

        if (pollError) {
            return NextResponse.json(
                { error: pollError.message },
                { status: 500 }
            );
        }

        // 4. Insert Options
        const optionsPayload = options.map(
            (opt: { text: string; color: string }) => ({
                poll_id: pollData.id,
                option_text: opt.text,
                option_color: opt.color || "#a855f7",
                Votes: 0,
            })
        );

        const { error: optionsError } = await supabase
            .from("VoteOptions")
            .insert(optionsPayload);

        if (optionsError) {
            return NextResponse.json(
                { error: optionsError.message },
                { status: 500 }
            );
        }

        return NextResponse.json({ pollId: pollData.id });

    } catch (err: any) {
        return NextResponse.json(
            { error: err.message || "Server error" },
            { status: 500 }
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Pretty much we do an insert in two tables where we insert into the Poll table and insert to the VoteOptions table, where the VoteOption has a Foriegn key linked to the Poll.

You may also noticed this part, which we will get to later:

Poll_Ended: false,


Part 2

When the user linked on an existing poll, this is what the structure look like:

{/* RESULTS */ }
<div className="p-4 sm:p-6 md:p-8">
    <h1 className="text-center text-xl font-semibold">
        Total Votes: {totalVotes}
    </h1>

    {options.map((opt) => {
        const votes = Number(opt.Votes) || 0;
        const percentage =
            totalVotes > 0 ? (votes / totalVotes) * 100 : 0;

        return (
            <div
                key={opt.id}
                className="flex justify-between items-center p-4 sm:p-5 shadow-md outline outline-black/5 dark:bg-gray-800 border-2 border-gray-80 dark:border-gray-700 m-2"
                style={{
                    background: `linear-gradient(to right, ${opt.option_color} ${percentage}%, transparent ${percentage}%)`,
                }}
            >
                <span className="font-medium bg-black text-white px-2 py-1 rounded text-sm sm:text-base">
                    {opt.option_text}: {votes}
                </span>
            </div>
        );
    })}
</div>

{/* VOTING FORM */ }
{
    !hasVoted && !pollEnded && (
        <form
            onSubmit={handleVote}
            className="p-4 sm:p-6 md:p-8 flex flex-col gap-2"
        >
            <h1 className="font-medium mb-2">Choose your Vote!</h1>

            {options.map((opt) => (
                <label
                    key={opt.id}
                    className="flex items-center gap-2 p-2 border-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                    <input
                        type="radio"
                        name="vote"
                        value={opt.id}
                        checked={selected === opt.id}
                        onChange={() => setSelected(opt.id)}
                        className="cursor-pointer"
                    />

                    <span className="flex-1 text-sm sm:text-base">
                        {opt.option_text}
                    </span>
                </label>
            ))}

            <button
                type="submit"
                disabled={loading}
                className="w-full bg-blue-500 text-white py-3 disabled:bg-gray-400 mt-5"
            >
                {loading ? "Submitting..." : "Submit Vote"}
            </button>
        </form>
    )
}

{/* MESSAGE */ }
{
    (message || hasVoted) && (
        <p className="mt-4 text-center text-sm p-4 sm:p-5">
            {message}
        </p>
    )
}

Enter fullscreen mode Exit fullscreen mode

It is structured similar to the Demo Poll I discuss on the last Dev Log. Most of it is trying to fetch data from the database and displaying it in the UI.

In another component, we have a timer set. If the timer has reach the end date (where the user has set the end date), it will set the boolean to true and it will remove the ability to vote on that poll.

const now = new Date();
const end = new Date(poll.Poll_EndDate);
const pollEnded = now >= end;

// update DB if not already ended
if (pollEnded && !poll.Poll_Ended) {
    await supabase
        .from("Poll")
        .update({ Poll_Ended: true })
        .eq("id", poll.id);
}

Enter fullscreen mode Exit fullscreen mode

Note: The feature of auto delete a poll will be implemented in the future.

And that's it! Future developments will continue after the end of the Spring Semester! I appreciate the feedback from the community and feel free to provide feedback if you haven't already!


Official Website

If you would love to see the project yourself, feel free to check out the link here: https://easypollvote.vercel.app

I recommend to put a fake email and a fake name if you are using the app. Everything works as intended! Check it out and feedback is greatly appreciated!


Any questions/comments/feedback? I would love to hear from you!

Note: This post is monitored by the University and therefore the repository is currently private until the early Summer!