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

推荐订阅源

人人都是产品经理
人人都是产品经理
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
N
News and Events Feed by Topic
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
博客园 - 叶小钗
B
Blog
Vercel News
Vercel News
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Microsoft Security Blog
Microsoft Security Blog
S
Securelist
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Palo Alto Networks Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
DataBreaches.Net
Cyberwarzone
Cyberwarzone
Engineering at Meta
Engineering at Meta
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Check Point Blog
A
About on SuperTechFans
W
WeLiveSecurity
The GitHub Blog
The GitHub Blog

Vercel News

Vercel Open Source Program: Winter 2026 cohort How Notion Workers run untrusted code at scale with Vercel Sandbox How we run Vercel's CDN in front of Discourse From idea to secure checkout in minutes with Stripe Building Slack agents can be easy Scaling redirects to infinity on Vercel Advancing Python typing Gamma builds design-first agents with Vercel How Avalara turns pipe dreams into patent-pending with v0 Keeping community human while scaling with agents How OpenEvidence built a healthcare AI that physicians actually trust Security boundaries in agentic architectures Skills Night: 69,000+ ways agents are getting smarter Video Generation with AI Gateway We Ralph Wiggumed WebStreams to make them 10x faster How Stably ships AI testing agents in hours, not weeks How we built AEO tracking for coding agents Anyone can build agents, but it takes a platform to run them Introducing Geist Pixel The Vercel AI Accelerator is back with $6m in credits Making agent-friendly pages with content negotiation The Vercel OSS Bug Bounty program is now available Introducing the new v0 Run untrusted code with Vercel Sandbox, now generally available How Stripe built a game-changing app in a single flight with v0 How Sensay went from zero to product in six weeks AGENTS.md outperforms skills in our agent evals Agent skills explained: An FAQ Testing if "bash is all you need" AWS databases are now live on the Vercel Marketplace and v0 Use Perplexity Web Search with Vercel AI Gateway Introducing: React Best Practices Nick Bogaty joins Vercel as Chief Revenue Officer How Mux shipped durable video workflows with their @mux/ai SDK How to build agents with filesystems and bash How we made v0 an effective coding agent Stopping the slow death of internal tools Building AI-Generated Pixel Trading Cards with Vercel AI Gateway We removed 80% of our agent’s tools AI SDK 6 Our $1 million hacker challenge for React2Shell Cline now runs on Vercel AI Gateway How to prompt v0 Build smarter workflows with Notion and v0 Vercel launches partner certification Inside Workflow DevKit: How framework integrations work React2Shell Security Bulletin | Vercel Knowledge Base Billions of requests: Black Friday-Cyber Monday 2025 Investing in the Python ecosystem AWS Databases coming to the Vercel Marketplace How we built the v0 iOS app Workflow Builder: Build your own workflow automation platform Vercel Open Source Program: Fall 2025 cohort Self-driving infrastructure Vercel collaborates with Google for Gemini 3 Pro Preview launch Vercel: The anti-vendor-lock-in cloud How Nous Research used BotID to block automated abuse at scale How AI Gateway runs on Fluid compute What we learned building agents at Vercel Build and deploy data applications on Snowflake with v0 BotID Deep Analysis catches a sophisticated bot network in real-time Vercel achieves TISAX AL2 compliance to serve automotive partners Bun runtime on Vercel Functions David Totten Joins Vercel to Lead Global Field Engineering Vercel Ship AI 2025 recap You can just ship agents AI agents and services on the Vercel Marketplace Built-in durability: Introducing Workflow Development Kit Zero-config backends on Vercel AI Cloud Introducing Vercel Agent: Your new Vercel teammate Update regarding Vercel service disruption on October 20, 2025 Agents at work, a partnership with Salesforce and Slack Running Next.js in ChatGPT: How to Build ChatGPT Apps Talha Tariq joins Vercel as CTO of Security Just another (Black) Friday Server rendering benchmarks: Fluid Compute and Cloudflare Workers Towards the AI Cloud: Our Series F Collaborating with Anthropic on Claude Sonnet 4.5 to power intelligent coding agents Preventing the stampede: Request collapsing in the Vercel CDN BotID uncovers hidden SEO poisoning How we made global routing faster with Bloom filters What you need to know about vibe coding Scale to one: How Fluid solves cold starts Addressing security & quality issues with MCP tools - Vercel AI agents at scale: Rox’s Vercel-powered revenue operating system Agentic Infrastructure Zero Data Retention on AI Gateway Optimizing Vercel Sandbox snapshots How Waldium made a blog platform work for humans and AI alike How FLORA shipped a creative agent on Vercel's AI stack Agent responsibly Making Turborepo 96% faster with agents, sandboxes, and humans Unified reporting for all AI Gateway usage new.website joins forces with v0 SERHANT.'s playbook for rapid AI iteration Two startups at global scale without DevOps Chat SDK brings agents to your users 360 billion tokens, 3 million customers, 6 engineers Meet the 2026 Vercel AI Accelerator Cohort Build knowledge agents without embeddings
Common mistakes with the Next.js App Router and how to fix them - Vercel – Vercel
Lee Robinson · 2024-01-08 · via Vercel News

6 min read

After talking to hundreds of developers and looking at thousands of Next.js repositories, I've noticed ten common mistakes when building with the Next.js App Router.

This post will share why these mistakes can happen, how to fix them, and some tips to help you understand the new App Router model.

Link to headingUsing Route Handlers with Server Components

Consider the following code for a Server Component:

app/page.tsx

export default async function Page() {

let res = await fetch('http://localhost:3000/api/data');

let data = await res.json();

return <h1>{JSON.stringify(data)}</h1>;

}

Fetching JSON data from a Route Handler in a Server Component.

This async component makes a request to a Route Handler to retrieve some JSON data:

app/api/data/route.ts

export async function GET(request: Request) {

return Response.json({ data: 'Next.js' });

}

A Route Handler that returns static JSON data.

There's two main issues with this approach:

  1. Both Route Handlers and Server Components run securely on the server. You don't need the additional network hop. Instead, you can call whatever logic you intended to place inside the Route Handler directly in the Server Component. This might be an external API or any Promise.

  2. Since this code is running on the server with Node.js, we need to provide the absolute URL for the fetch versus a relative URL. In reality, we wouldn't hardcode localhost here, but instead need to have some conditional check based on the environment we're in. This is unnecessary since you can call the logic directly.

Instead, prefer to do the following:

app/page.tsx

export default async function Page() {

// call your async function directly

let data = await getData(); // { data: 'Next.js' }

// or call an external API directly

let data = await fetch('https://api.vercel.app/blog')

// ...

}

Server Components are able to fetch data directly.

Link to headingStatic or dynamic Route Handlers

Route Handlers are cached by default when using the GET method. This can often be confusing for existing Next.js developers moving from the Pages Router and API Routes.

For example, the following code will be prerendered during next build:

app/api/data/route.ts

export async function GET(request: Request) {

return Response.json({ data: 'Next.js' });

}

A Route Handler that returns static JSON data.

This JSON data will not change until another build has completed. Why is that?

You can consider Route Handlers the building blocks of pages. For a given request to a route, you want to handle it. Next.js has further abstractions on top of Route Handlers like pages and layouts. This is why Route Handlers are static by default (like pages) and share the same route segment configuration options.

This functionality unlocks some new features previously not possible with API Routes in the Pages Router. For example, you can have Route Handlers that produce JSON, or txt files, or really any file, which can be computed and prerendered during the build. The statically generated file is then automatically cached, and even periodically updated if desired.

app/api/data/route.ts

export async function GET(request: Request) {

let res = await fetch('https://api.vercel.app/blog');

let data = await res.json();

return Response.json(data);

}

Return a list of blog posts as JSON data.

Further, this means the Route Handlers are compatible with Static Exports where you can deploy your Next.js application anywhere that supports static file hosting.

Link to headingRoute Handlers and Client Components

You might think you need to use Route Handlers with Client Components, since they cannot be marked async and fetch or mutate data. Rather than needing to write a fetch and create a Route Handler, you can instead call Server Actions directly from Client Components.

app/user-form.tsx

'use client';

import { save } from './actions';

export function UserForm() {

return (

<form action={save}>

<input type="text" name="username" />

<button>Save</button>

</form>

);

}

A form and input to save a name.

This works with both forms as well as event handlers:

app/user-form.tsx

'use client';

import { save } from './actions';

export function UserForm({ username }) {

async function onSave(event) {

event.preventDefault();

await save(username);

}

return <button onClick={onSave}>Save</button>;

}

Server Actions can be called from event handlers.

Link to headingUsing Suspense with Server Components

Consider the following Server Component. Where should Suspense be placed to define what fallback UI will be shown while the data is being fetched?

app/page.tsx

async function BlogPosts() {

let data = await fetch('https://api.vercel.app/blog');

let posts = await data.json();

return (

<ul>

{posts.map((post) => (

<li key={post.id}>{post.title}</li>

))}

</ul>

);

}

export default function Page() {

return (

<section>

<h1>Blog Posts</h1>

<BlogPosts />

</section>

);

}

A page which contains an async component with data fetching.

If you guessed inside of the Page component, you were correct. The Suspense boundary needs to be placed higher than the async component doing the data fetching. It will not work if the boundary is inside of the async component.

app/page.tsx

import { Suspense } from 'react';

async function BlogPosts() {

let data = await fetch('https://api.vercel.app/blog');

let posts = await data.json();

return (

<ul>

{posts.map((post) => (

<li key={post.id}>{post.title}</li>

))}

</ul>

);

}

export default function Page() {

return (

<section>

<h1>Blog Posts</h1>

<Suspense fallback={<p>Loading...</p>}>

<BlogPosts />

</Suspense>

</section>

);

}

Using Suspense with React Server Components.

In the future with Partial Prerendering, this pattern will start to become more common, including defining which components should be prerendered and which should run on-demand.

import { unstable_noStore as noStore } from 'next/cache';

async function BlogPosts() {

noStore(); // This component should run dynamically

let data = await fetch('https://api.vercel.app/blog');

let posts = await data.json();

return (

<ul>

{posts.map((post) => (

<li key={post.id}>{post.title}</li>

))}

</ul>

);

}

Opt-into dynamic rendering inside async components.

Link to headingUsing the incoming request

Since the incoming request object is not able to be accessed from a Server Component, it might not be obvious how to read parts of the incoming request. This could lead to using client hooks like useSearchParams unnecessarily.

There are specific functions and props to the Server Component which allow you to access the incoming request. For example:

app/blog/[slug]/page.tsx

export default function Page({

params,

searchParams,

}: {

params: { slug: string }

searchParams: { [key: string]: string | string[] | undefined }

}) {

return <h1>My Page</h1>

}

Reading parts of the URL and the search parameters.

Link to headingUsing Context providers with App Router

You might want to use React Context or are using an external dependency which relies on context. Two common mistakes I've seen are trying to use context with Server Components (unsupported) and the placement of the provider in the App Router.

To allow for your Server and Client Components to interleave, it's important to make your provider (or multiple providers) be a separate Client Component which takes children as a prop and renders them. For example:

app/theme-provider.tsx

'use client';

import { createContext } from 'react';

export const ThemeContext = createContext({});

export default function ThemeProvider({

children,

}: {

children: React.ReactNode;

}) {

return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>;

}

A Client Component that uses React Context.

Then, with your provider in a separate file as a Client Component, you can import and use this component inside of your layout:

app/layout.tsx

import ThemeProvider from './theme-provider';

export default function RootLayout({

children,

}: {

children: React.ReactNode;

}) {

return (

<html>

<body>

<ThemeProvider>{children}</ThemeProvider>

</body>

</html>

);

}

A root layout that weaves a client context provider and Server Component children.

With the provider rendered at the root, all other Client Components throughout your app will be able to consume this context. And notably, this configuration still allows for other Server Components (including the page) lower in the tree.

Link to headingUsing Server and Client Components together

Many React and Next.js developers are learning how to use Server and Client Components for the first time. It's expected there might be some mistakes and opportunities to learn this new model!

For example, consider the following page:

app/page.tsx

export default function Page() {

return (

<section>

<h1>My Page</h1>

</section>

);

}

A Server Component page.

This is a Server Component. While that comes with new functionality like being able to fetch data directly in the component, it also means certain client-side React functionalities aren't available.

For example, consider creating a button that is a counter. This would need to be a new Client Component file marked with the "use client" directive at the top:

app/counter.tsx

'use client';

import { useState } from 'react';

export function Counter() {

const [count, setCount] = useState(0);

return (

<div>

<p>Count: {count}</p>

<button onClick={() => setCount(count + 1)}>Increment</button>

</div>

);

}

A Client Component button that increments a count.

You can then import and use this component in your page:

app/page.tsx

import { Counter } from './counter';

export default function Page() {

return (

<section>

<h1>My Page</h1>

<Counter />

</section>

);

}

Using a Client Component from a Server Component.

The page is a Server Component and the <Counter> is a Client Component. Great! What about components lower in the tree than the counter? Can those be Server Components? Yes, through composition:

app/page.tsx

import { Counter } from './counter';

function Message() {

return <p>This is a Server Component</p>;

}

export default function Page() {

return (

<section>

<h1>My Page</h1>

<Counter>

<Message />

</Counter>

</section>

);

}

Children of a Client Component can be Server Components.

Children of a Client Component can be a Server Component! Here's the updated counter:

app/counter.tsx

'use client';

import { useState } from 'react';

export function Counter({ children }: { children: React.ReactNode }) {

const [count, setCount] = useState(0);

return (

<div>

<p>Count: {count}</p>

<button onClick={() => setCount(count + 1)}>Increment</button>

{children}

</div>

);

}

The counter now accepts children and displays them.

Link to headingAdding “use client” unnecessarily

Building off the previous example, does that mean that we need to add the "use client" directive everywhere?

When the "use client" directive is added, you pass into the "client boundary" giving you the ability to run client-side JavaScript (i.e. using React hooks or state). Client Components are still prerendered on the server, similar to components in the Next.js Pages Router.

Since you're already in the client boundary, siblings of the <Counter> would become Client Components. You don't need to add "use client" to every file. This might be an approach taken for incremental adoption of the App Router, where a component high up the tree becomes a Client Component and it becomes weave child Server Components further down.

Link to headingNot revalidating data after mutations

The Next.js App Router includes a complete model for fetching, caching, and revalidating data. As developers are still learning this new model, and we're continuing to make improvements based on their feedback, one common mistake I've seen is forgetting to revalidate data after a mutation.

For example, consider the following Server Component. It displays a form, which uses a Server Action to handle the submission and create a new entry in a Postgres database.

app/page.tsx

export default function Page() {

async function create(formData: FormData) {

'use server';

let name = formData.get('name');

await sql`INSERT INTO users (name) VALUES (${name})`;

}

return (

<form action={create}>

<input name="name" type="text" />

<button type="submit">Create</button>

</form>

);

}

A Server Action that inserts the name into a Postgres database.

After the form is submitted and the insertion happens successfully, would the data displaying the list of names automatically update? No, not unless we tell Next.js to. For example:

app/page.tsx

import { revalidatePath } from 'next/cache';

export default async function Page() {

let names = await sql`SELECT * FROM users`;

async function create(formData: FormData) {

'use server';

let name = formData.get('name');

await sql`INSERT INTO users (name) VALUES (${name})`;

revalidatePath('/');

}

return (

<section>

<form action={create}>

<input name="name" type="text" />

<button type="submit">Create</button>

</form>

<ul>

{names.map((name) => (

<li>{name}</li>

))}

</ul>

</section>

);

}

Revalidating data inside of a Server Action.

Link to headingRedirects inside of try/catch blocks

When running server-side code, like a Server Component or a Server Action, you might want to redirect if a resource is not available or after a successful mutation.

The redirect() function does not require you to use return redirect() as it uses the TypeScript never type. Further, internally this function throws a Next.js specific error. This means you should handle redirecting outside of try/catch blocks.

For example, if you are trying to redirect inside of a Server Component, it might look like this:

app/page.tsx

import { redirect } from 'next/navigation';

async function fetchTeam(id) {

const res = await fetch('https://...');

if (!res.ok) return undefined;

return res.json();

}

export default async function Profile({ params }) {

const team = await fetchTeam(params.id);

if (!team) {

redirect('/login');

}

// ...

}

Redirecting from a Server Component.

Alternatively, if you're trying to redirect from a Client Component, this should happen inside of a Server Action and not in an event handler:

app/client-redirect.tsx

'use client';

import { navigate } from './actions';

export function ClientRedirect() {

return (

<form action={navigate}>

<input type="text" name="id" />

<button>Submit</button>

</form>

);

}

Redirecting in a Client Component through a Server Action.

app/actions.ts

'use server';

import { redirect } from 'next/navigation';

export async function navigate(data: FormData) {

redirect('/posts');

}

A Server Action that redirects to a new route.

Link to headingConclusion

The Next.js App Router is a new approach for building React applications and there's a handful of new concepts to learn. If you've made any of these mistakes, don't feel discouraged. I've made them as well learning how the model works.

If you want to keep learning more and apply this knowledge, check out our Next.js Learn course to build a real dashboard application with the App Router.