~2 min read • Updated Oct 31, 2025
1. What Is connection?
connection() is a function in Next.js that delays rendering until a real user request is received. It’s useful when you want runtime behavior without using Dynamic APIs. This ensures the output is generated at request time, not during build.
Example:
// app/page.tsx
import { connection } from 'next/server'
export default async function Page() {
await connection()
const rand = Math.random()
return <span>{rand}</span>
}In this example, Math.random() runs at runtime, and the result is excluded from prerendering.
2. Cookie API in Next.js
The cookies() function lets you read incoming cookies in Server Components and read/write outgoing cookies in Server Actions or Route Handlers.
Reading a cookie:
const cookieStore = await cookies()
const theme = cookieStore.get('theme')Reading all cookies:
cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))Checking if a cookie exists:
const hasCookie = cookieStore.has('theme')Setting a cookie (only in Server Action or Route Handler):
cookieStore.set('name', 'lee', { secure: true })Deleting a cookie:
cookieStore.delete('name')cookieStore.set('name', '')cookieStore.set('name', 'value', { maxAge: 0 })
3. Cookie Behavior Notes
cookies()is async in Next.js 15 and returns a promise- Using cookies makes the route dynamic
- Setting or deleting cookies must happen in Server Actions or Route Handlers
- Cookies are stored on the client; the server only sends instructions via headers
4. Cookie Behavior in Server Actions
After setting or deleting a cookie in a Server Action, Next.js re-renders the current page and layout on the server to reflect the new cookie value. To refresh cached data, use revalidatePath or revalidateTag.
Conclusion
The connection() function lets you defer rendering until runtime, and the cookies API gives you powerful tools for managing user state on the server. Together, they help you build dynamic, secure, and personalized experiences in Next.js.
Written & researched by Dr. Shahin Siami