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

推荐订阅源

F
Fortinet All Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threatpost
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
人人都是产品经理
人人都是产品经理
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Cloudflare Blog
N
News and Events Feed by Topic
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
AWS News Blog
AWS News Blog
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Spread Privacy
Spread Privacy
J
Java Code Geeks
博客园 - 聂微东
T
Tor Project blog
宝玉的分享
宝玉的分享
博客园 - 叶小钗
Webroot Blog
Webroot Blog
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Heimdal Security Blog
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
I
InfoQ
Security Latest
Security Latest
Martin Fowler
Martin Fowler
Hacker News: Ask HN
Hacker News: Ask HN
P
Privacy International News Feed
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cisco Blogs
H
Help Net Security
L
LINUX DO - 最新话题
L
LINUX DO - 热门话题

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
Lakera Guard in 30 Lines — Production-Ready AI Safety for Next.js Route Handlers (2026)
Vibe-Start · 2026-05-02 · via DEV Community

Vibe-Start

🛡 Why Your AI Route Handlers Need a Guard Layer

The moment you ship /api/chat in Next.js App Router, you have a structural security problem. User input flows directly into your LLM prompt, which means prompt injection, PII leakage, and system-prompt overrides are exposed without a single line of malicious code. OWASP's 2026 Agentic Top 10 (ASI) covers exactly this surface in ASI01 (Goal Hijack) and ASI02 (Memory Poisoning).

Regex blocklists fall apart against variant inputs ("!gnore previous instructions", base64-encoded payloads, newline tricks), and writing "refuse harmful requests" in your system prompt is trivially bypassed. The 2026 standard is a separate validation layer in front of the LLM call: only validated inputs reach the model. Lakera Guard delivers that validation as a one-call SaaS — the lowest-friction option on the market.

📋 The 4 Risks Lakera Guard Catches

POST text to the Lakera Guard API and you get back a per-category risk score (0.0 to 1.0). Standard policy: block above 0.5, pass below.

Category Risk it catches OWASP ASI mapping
prompt_injection System-prompt override, mission swap ASI01 Goal Hijack
jailbreak Safety guideline bypass (DAN, "ignore previous") ASI01 / ASI06
pii Emails, phone, SSN, card numbers in input ASI02 Memory Poisoning
moderation Violence, self-harm, hate, sexual content ASI05 Cascading Hallucination

The free tier covers 10,000 calls per month — plenty for personal projects or a side SaaS during validation. Switch to paid when production traffic crosses that line.

🔑 Setup — 5 Minutes End to End

1. Get an API key

Sign up at lakera.ai → Dashboard → API Keys → create a new key. Keys start with the lak_ prefix.

2. Add the env var

# .env.local
LAKERA_GUARD_API_KEY=lak_your_key_here

Enter fullscreen mode Exit fullscreen mode

Don't commit .env.local. On Vercel, add the same variable in Project Settings → Environment Variables. LLM calls in this guide route through Vercel AI Gateway (OIDC) — no OpenAI/Anthropic provider keys in code. One vercel env pull .env.local provisions the VERCEL_OIDC_TOKEN and you're done.

3. Use fetch directly — zero dependencies

Lakera ships an SDK, but for Edge Runtime compatibility plain fetch is the safer choice. No node_modules bloat and the same code runs identically on Edge.

// lib/lakera.ts
type GuardCategory = "prompt_injection" | "jailbreak" | "pii" | "moderation";

type GuardResult = {
  flagged: boolean;
  categories: Record<GuardCategory, number>;
};

export async function lakeraGuard(input: string): Promise<GuardResult> {
  const res = await fetch("https://api.lakera.ai/v2/guard", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.LAKERA_GUARD_API_KEY}`,
    },
    body: JSON.stringify({ messages: [{ role: "user", content: input }] }),
  });

  if (!res.ok) throw new Error(`Lakera Guard ${res.status}`);
  return res.json() as Promise<GuardResult>;
}

Enter fullscreen mode Exit fullscreen mode

That's the entire helper. Reuse this 14-line file from every Route Handler that touches an LLM.

💻 30-Line Integration — App Router Route Handler

The simplest one-shot chat endpoint with Lakera Guard wired in. User message arrives → ① Lakera validates → ② if allowed, OpenAI is called → ③ if blocked, return 422.

// app/api/chat/route.ts
import { NextResponse } from "next/server";
import { generateText } from "ai";
import { lakeraGuard } from "@/lib/lakera";

export const runtime = "edge";

export async function POST(req: Request): Promise<Response> {
  const { message } = (await req.json()) as { message: string };

  const guard = await lakeraGuard(message);
  if (guard.flagged) {
    return NextResponse.json(
      { error: "Input blocked by safety check" },
      { status: 422 }
    );
  }

  const { text } = await generateText({
    model: "openai/gpt-5.4",
    prompt: message,
  });

  return NextResponse.json({ reply: text });
}

Enter fullscreen mode Exit fullscreen mode

The entire defense is if (guard.flagged) return 422. Closing the gate before the LLM call prevents wasted tokens, latency, and log pollution all at once. The model is specified as a plain "provider/model" string — AI SDK v6 routes this through the AI Gateway automatically, with no provider SDK import and no API key in code. In production, omit category names from the 422 body — exposing them gives bypass attempts a free training signal.

🌊 Streaming Chat — Vercel AI SDK Integration

Real chat UIs stream. With Vercel AI SDK's streamText, the question is where to put the guard, and the answer is before the stream opens. Output validation belongs in a separate layer.

// app/api/chat-stream/route.ts
import { streamText, convertToModelMessages, type UIMessage } from "ai";
import { lakeraGuard } from "@/lib/lakera";

export const runtime = "edge";

export async function POST(req: Request): Promise<Response> {
  const { messages } = (await req.json()) as { messages: UIMessage[] };

  const lastUser = messages.filter((m) => m.role === "user").pop();
  const lastUserText = lastUser?.parts
    .filter((p) => p.type === "text")
    .map((p) => p.text)
    .join("\n");

  if (!lastUserText) return new Response("No user text", { status: 400 });

  const guard = await lakeraGuard(lastUserText);
  if (guard.flagged) {
    return new Response(JSON.stringify({ error: "blocked" }), {
      status: 422,
      headers: { "Content-Type": "application/json" },
    });
  }

  const result = streamText({
    model: "openai/gpt-5.4",
    messages: convertToModelMessages(messages),
  });

  return result.toUIMessageStreamResponse();
}

Enter fullscreen mode Exit fullscreen mode

Two AI SDK v6 essentials are baked in here. ① The client sends UIMessage[], where each message has a parts array (not a content string) — extract user text by filtering parts of type: "text". ② streamText returns a result whose toUIMessageStreamResponse() is what useChat clients expect (the older toDataStreamResponse() was renamed in v6). Once a stream opens it's hard to cleanly cut tokens mid-flight, so blocking at the input stage wins on both UX and cost. Output-side risks (model emitting PII, model complying with jailbreak) belong in a downstream post-processing layer.

⚙️ Cost & Latency — Real Numbers

Numbers worth knowing before you adopt this, because they make decisions faster.

Metric Value Notes
Average API latency 80–120ms (us-east) Add ~100ms from APAC
Free tier 10,000 calls/month Enough for solo side projects
Paid entry $99/month (50,000 calls) ~$0.002 per call
Edge Runtime ✅ Fully compatible fetch-based, no cold start hit
Response payload ~300 bytes Negligible

100–200ms of guard latency disappears next to first-token LLM latency (typically 500–1500ms). If you still want to shave it, pin your Edge Function region to us-east-1 to colocate with the Lakera endpoint.

🚀 Production Checklist

Five things to verify before you ship. Five-minute review.

  1. Fail-open or fail-closed? What happens if the Lakera API is down? Decide explicitly: security-first → fail-closed (block on error); availability-first → fail-open (pass + log).
  2. Don't leak block reasons — Strip categories and scores from the 422 response. Exposing them hands bypass attempts a feedback loop.
  3. Mask blocked input in logs — Persisting raw blocked content puts log readers in front of malicious payloads. Hash or truncate.
  4. Track separately from rate limits — Lakera blocks are likely intentional attacks. Count them per-IP/per-account distinct from generic rate limits, and ramp blocking duration on repeat offenders.
  5. Alert on quota — Wire an alert at 80% of your monthly quota. A traffic spike that you only notice on next month's invoice is an avoidable surprise.

For the broader OWASP ASI checklist that covers permissions, logging, and human-approval gates, pair this article with the 5-minute audit guide.

📝 Next Layers

Lakera Guard is the first input-validation layer. Once your runtime is stable, layer in:

  • Output validation — Verify model responses don't contain PII (Lakera can score outputs too)
  • Call logging — Langfuse or Helicone auto-records every call's I/O, cost, and latency (covers ASI09 Untraceability)
  • Human-approval gates — Wire Slack-bot approval for risky tools like payment, external send (covers ASI06 / ASI10)
  • NeMo Guardrails — Policy-as-code over conversation flow itself. YAML overhead, but strong for complex agents

Stack all four and you cover ~90% of OWASP ASI Top 10 in production.


Originally published on vibe-start.com. I'm building VibeStart — a 30-minute path for non-developers to start AI-assisted coding.