Code Block

Display code and terminal output with an optional header, line numbers, and copy button.

app/api/chat/route.ts
import { streamText } from "ai"

export async function POST(request: Request) {
  const { messages } = await request.json()

  const result = streamText({
    model: "anthropic/claude-sonnet-4.5",
    system: "You are a helpful assistant. Answer in one short paragraph.",
    messages,
  })

  return result.toUIMessageStreamResponse()
}

Usage

Load the styles

Load a full Basecoat style bundle, or import base/base.css, components/code-block.css, components/button.css, components/scrollbar.css, and one style pack after Tailwind.

Add the code block

Use .code-block around native <pre><code>. Add a semantic <header> or <footer> when needed. Use Button for actions and Scroll Area’s .scrollbar on the focusable <pre>.

<div class="code-block">
  <header>
    <span>Terminal</span>
    <div>
      <button type="button" class="btn" data-variant="ghost" data-size="xs" data-copy>Copy</button>
    </div>
  </header>
  <pre class="scrollbar" tabindex="0" aria-label="Terminal output"><code>npm run build</code></pre>
</div>

For syntax colors, see Syntax highlighting.

Enable copying (optional)

Add data-copy to the button that copies the block. Include the Basecoat runtime and code-block.js, or the full all.js bundle. Copy uses the Clipboard API, which requires HTTPS or localhost; failure is announced without pretending the copy succeeded. Without JavaScript, the code remains selectable.

HTML structure

Use a <span> for the header title and a <div> for actions. An actions <div> directly inside .code-block floats at the top end, appearing on hover, keyboard focus, or touch devices.

Scrollable code has a CSS edge fade in browsers with scroll-driven animations. Wrapping moves the fade to the vertical axis.

Line numbers are off by default. To opt in, add data-line-numbers to <pre> and wrap each line in a direct <span> inside <code>. Preserve real newline characters between lines, including empty lines. CSS counters supply the visual numbers, which are excluded from both native selection and the Copy button. Plain text needs no line wrappers; use them only for numbering, highlighting, or line-specific utilities.

Examples

Basic

$ pnpm build
> next build

 ✓ Compiled successfully in 4.2s
 ✓ Generating static pages (12/12)

Route (app)                Size  First Load JS
┌ ○ /                    1.9 kB         112 kB
├ ○ /_not-found           993 B         103 kB
└ ƒ /api/chat             141 B         102 kB

Use a header for a filename or a label. The Copy button here copies the displayed terminal output.

Terminal
$ pnpm add ai @ai-sdk/react zod
Packages: +14
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0

Actions

The header can hold any buttons or links your app needs. Try Wrap lines to switch the lint output between wrapped lines and horizontal scrolling. Download saves the output as lint.log using a native download link. Copy copies the same text to the clipboard. Basecoat handles Copy. Your app supplies the behavior for custom actions.

Terminal
$ pnpm lint
apps/web/components/message-list.tsx
  18:22  error  'messages' is possibly 'undefined'. Add a guard before calling map  @typescript-eslint/no-unsafe-call
  42:7   warning  React Hook React.useEffect has a missing dependency: 'scrollToBottom'  react-hooks/exhaustive-deps

✖ 2 problems (1 error, 1 warning)

Floating actions

$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
dependencies:
+ @ai-sdk/react 3.0.12
+ ai 6.0.12
+ zod 4.1.12
Done in 2.8s using pnpm v10.18.0

Line numbers

Add data-line-numbers to opt in. Like upstream, unnumbered code is the default.

{
  "name": "chat",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build"
  }
}

Wrapping

The first block scrolls horizontally. Adding data-wrap to the second block lets the same error message fit its width.

Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.
Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.

Highlighted lines

Apply ordinary utilities to the lines you want to emphasize. This recipe uses bg-foreground/5 and an outline in forced-colors mode. Unlike upstream’s line variants, these are example classes, not a Code Block API.

export default {
  experimental: {
    reactCompiler: true,
    viewTransition: true,
  },
  images: {
    remotePatterns: [{ hostname: "avatars.githubusercontent.com" }],
  },
}

Diff

Render the patch as text, including its + and - prefixes, and use utilities for line backgrounds. The prefixes keep changes distinguishable without color. Native selection and the Copy button both copy the displayed patch, including its prefixes. No diff parser or dedicated variants are included.

components/greeting.tsx
 export function Greeting({ name }: { name: string }) {
-  return <p>Hello, {name}</p>
+  return <p className="text-sm text-muted-foreground">
+    Hello, {name}!
+  </p>
 }

Height

Use ordinary height utilities to constrain a block. The native scroll area remains keyboard-accessible.

Logs
[01] GET /api/chat 200 in 12ms
[02] GET /api/chat 200 in 19ms
[03] GET /api/chat 200 in 26ms
[04] GET /api/chat 200 in 33ms
[05] GET /api/chat 200 in 40ms
[06] GET /api/chat 200 in 47ms
[07] GET /api/chat 200 in 14ms
[08] GET /api/chat 200 in 21ms
[09] GET /api/chat 200 in 28ms
[10] GET /api/chat 200 in 35ms
[11] GET /api/chat 200 in 42ms
[12] GET /api/chat 200 in 49ms
[13] GET /api/chat 200 in 16ms
[14] GET /api/chat 200 in 23ms
[15] GET /api/chat 200 in 30ms
[16] GET /api/chat 200 in 37ms
[17] GET /api/chat 200 in 44ms
[18] GET /api/chat 200 in 51ms
[19] GET /api/chat 200 in 18ms
[20] GET /api/chat 200 in 25ms
[21] GET /api/chat 200 in 32ms
[22] GET /api/chat 200 in 39ms
[23] GET /api/chat 200 in 46ms
[24] GET /api/chat 200 in 13ms
[25] GET /api/chat 200 in 20ms
[26] GET /api/chat 200 in 27ms
[27] GET /api/chat 200 in 34ms
[28] GET /api/chat 200 in 41ms
[29] GET /api/chat 200 in 48ms
[30] GET /api/chat 200 in 15ms
[31] GET /api/chat 200 in 22ms
[32] GET /api/chat 200 in 29ms
[33] GET /api/chat 200 in 36ms
[34] GET /api/chat 200 in 43ms
[35] GET /api/chat 200 in 50ms
[36] GET /api/chat 200 in 17ms
[37] GET /api/chat 200 in 24ms
[38] GET /api/chat 200 in 31ms
[39] GET /api/chat 200 in 38ms
[40] GET /api/chat 200 in 45ms

Size

Terminal
$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0
Terminal
$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0

Destructive

Error
TypeError: Cannot read properties of undefined (reading 'map')
    at MessageList (components/message-list.tsx:18:22)
    at renderWithHooks (react-dom.development.js:16305:18)

Syntax highlighting

Code Block displays plain text by default. To color the keys, strings, and numbers in this JSON example, the docs run Shiki at build time and place its colored spans inside <pre><code>. The browser receives ordinary HTML. Basecoat styles the block, and the Shiki theme supplies the token colors.

getWeather output
{
  "location": "San Francisco",
  "temperature": 18,
  "unit": "celsius",
  "conditions": ["fog", "wind"]
}

RTL

The header follows the page direction. Code always reads left to right.

ثبّت الحزم، ثم شغّل خادم التطوير.

الطرفية
pnpm add ai @ai-sdk/react zod
pnpm dev