- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Attachment
- Avatar
- Badge
- Breadcrumb
- Bubble
- Button
- Button Group
- Calendar
- Card
- Carousel
- Chart
- Checkbox
- Code Block
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Direction
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Kbd
- Label
- Marker
- Menubar
- Message
- Message Scroller
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Questionnaire
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toast
- Toggle
- Toggle Group
- Tooltip
- Trace
- Typography
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()}"use client"
import * as React from "react""use client"
import * as React from "react"
import { DownloadIcon, FileCodeIcon, WrapTextIcon } from "lucide-react"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import { Button } from "@/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const code = `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()
}`
function download(value: string, filename: string) {
const url = URL.createObjectURL(new Blob([value], { type: "text/plain" }))
const link = document.createElement("a")
link.href = url
link.download = filename
link.click()
URL.revokeObjectURL(url)
}
export function CodeBlockDemo() {
const [wrap, setWrap] = React.useState(false)
const lines = useHighlightedCode(code, "ts")
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<FileCodeIcon />
app/api/chat/route.ts
</CodeBlockTitle>
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap}
className="aria-pressed:text-foreground"
onClick={() => setWrap(!wrap)}
>
<WrapTextIcon />
</Button>
<Button
variant="ghost"
size="icon-xs"
aria-label="Download"
onClick={() => download(code, "route.ts")}
>
<DownloadIcon />
</Button>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap={wrap} lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine
key={index}
variant={index >= 5 && index <= 9 ? "highlighted" : "default"}
>
{line}
</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
CodeBlock displays code, terminal output, logs and diffs. It has a header with a title and actions, line numbers, wrapping, diff and highlighted lines, and a small size for tool output in a Trace.
Syntax highlighting is optional and lives in a separate hook, so a block that only shows plain output stays small.
Installation#
pnpm dlx shadcn@latest add code-block
Install the following dependencies:
pnpm add shiki
Install the required shadcn/ui dependencies:
pnpm dlx shadcn@latest add button
Copy and paste the following code into your project.
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { CheckIcon, CopyIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
const codeBlockVariants = cva(
"group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-2xl text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/30 data-[size=sm]:rounded-xl data-[size=sm]:text-xs",
{
variants: {
variant: {
default:
"bg-muted text-foreground ring-1 ring-foreground/5 dark:ring-foreground/10",
destructive:
"bg-destructive/5 text-destructive ring-1 ring-destructive/15 dark:bg-destructive/10 dark:ring-destructive/20",
},
},
defaultVariants: {
variant: "default",
},
}
)
function CodeBlock({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {
return (
<div
data-slot="code-block"
data-variant={variant}
data-size={size}
className={cn(codeBlockVariants({ variant }), className)}
{...props}
/>
)
}
function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-header"
className={cn(
"flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 group-data-[variant=destructive]/code-block:text-destructive *:has-[>[data-slot=code-block-title]]:min-w-0",
className
)}
{...props}
/>
)
}
function CodeBlockTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-title"
className={cn(
"min-w-0 truncate font-sans text-sm font-medium text-foreground group-data-[size=sm]/code-block:text-xs group-data-[variant=destructive]/code-block:text-destructive [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5 *:[svg]:me-1.5",
className
)}
{...props}
/>
)
}
function CodeBlockActions({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-actions"
className={cn(
"-my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1 *:data-[slot=button]:hover:bg-foreground/5 dark:*:data-[slot=button]:hover:bg-foreground/10 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10",
className
)}
{...props}
/>
)
}
function CodeBlockCopyButton({
value,
variant = "ghost",
size = "icon-xs",
className,
onClick,
...props
}: React.ComponentProps<typeof Button> & { value: string }) {
const [copied, setCopied] = React.useState(false)
React.useEffect(() => {
if (!copied) {
return
}
const timeout = setTimeout(() => setCopied(false), 2000)
return () => clearTimeout(timeout)
}, [copied])
return (
<>
<Button
data-slot="code-block-copy-button"
data-copied={copied || undefined}
variant={variant}
size={size}
aria-label={copied ? "Copied" : "Copy"}
className={cn(
"hover:bg-foreground/5 dark:hover:bg-foreground/10",
className
)}
onClick={(event) => {
onClick?.(event)
navigator.clipboard
.writeText(value)
.then(() => setCopied(true))
.catch(() => {})
}}
{...props}
>
{copied ? <CheckIcon /> : <CopyIcon />}
</Button>
<span aria-live="polite" className="sr-only">
{copied ? "Copied" : ""}
</span>
</>
)
}
function CodeBlockContent({
className,
children,
style,
wrap = false,
lineNumbers = false,
startLine = 1,
...props
}: React.ComponentProps<"pre"> & {
wrap?: boolean
lineNumbers?: boolean
startLine?: number
}) {
return (
<pre
data-slot="code-block-content"
data-wrap={wrap || undefined}
data-numbered={lineNumbers || undefined}
dir="ltr"
tabIndex={0}
style={{ counterReset: `line ${startLine - 1}`, ...style }}
className={cn(
"min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto px-4 py-4 text-start font-mono leading-relaxed outline-none group-has-data-[slot=code-block-footer]/code-block:pb-2 group-has-data-[slot=code-block-header]/code-block:pt-2 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
className
)}
{...props}
>
<code
data-slot="code-block-code"
className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
>
{lineNumbers && typeof children === "string"
? children
.replace(/\n$/, "")
.split("\n")
.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))
: children}
</code>
</pre>
)
}
const codeBlockLineVariants = cva(
"relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:gap-x-3 in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']",
{
variants: {
variant: {
default: "",
added: "bg-foreground/5 after:content-['+']",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
highlighted: "bg-foreground/5",
},
},
defaultVariants: {
variant: "default",
},
}
)
function CodeBlockLine({
className,
variant = "default",
children,
...props
}: React.ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>) {
// An empty line holds a newline so copying a selection keeps blank lines.
const empty =
children === undefined ||
children === null ||
children === "" ||
(Array.isArray(children) && children.length === 0)
return (
<span
data-slot="code-block-line"
data-variant={variant}
className={cn(codeBlockLineVariants({ variant }), className)}
{...props}
>
<span data-slot="code-block-line-content" className="min-w-0">
{empty ? "\n" : children}
</span>
</span>
)
}
function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="code-block-footer"
className={cn(
"flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
className
)}
{...props}
/>
)
}
export {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
CodeBlockLine,
CodeBlockFooter,
}
import * as React from "react"
import { loadHighlighter } from "@/lib/highlighter"
export function useHighlightedCode(value: string, language: string) {
// A trailing newline would render as an extra empty line.
const code = value.endsWith("\n") ? value.slice(0, -1) : value
const [loaded, setLoaded] = React.useState<{
language: string
highlighter: Awaited<ReturnType<typeof loadHighlighter>>
} | null>(null)
const highlighter = loaded?.language === language ? loaded.highlighter : null
React.useEffect(() => {
let cancelled = false
loadHighlighter(language)
.then((next) => {
if (!cancelled) {
setLoaded({ language, highlighter: next })
}
})
.catch(() => {})
return () => {
cancelled = true
}
}, [language])
// The complete lines, highlighted. While the code streams, only the new
// lines are tokenized, starting from the grammar state of the last one.
const [done, setDone] = React.useState<{
highlighter: typeof highlighter
text: string
lines: React.ReactNode[]
state?: Parameters<NonNullable<typeof highlighter>["highlight"]>[1]
}>({ highlighter: null, text: "", lines: [] })
let next = done
if (next.highlighter !== highlighter || !code.startsWith(next.text)) {
next = { highlighter, text: "", lines: [] }
}
const end = code.lastIndexOf("\n") + 1
if (highlighter && end > next.text.length) {
const result = highlighter.highlight(
code.slice(next.text.length, end - 1),
next.state
)
next = {
highlighter,
text: code.slice(0, end),
lines: [...next.lines, ...result.lines],
state: result.state,
}
}
if (next !== done) {
setDone(next)
}
// The last line is still being written, so it is tokenized on every render.
const tail = code.slice(end)
return React.useMemo(() => {
if (!highlighter) {
return code.split("\n")
}
return [...next.lines, highlighter.highlight(tail, next.state).lines[0]]
}, [code, highlighter, next, tail])
}
import * as React from "react"
import {
createHighlighterCore,
type GrammarState,
type HighlighterCore,
} from "shiki/core"
import { createJavaScriptRegexEngine } from "shiki/engine/javascript"
// Add the languages you need. Each one loads the first time it is used.
const languages = {
bash: () => import("shiki/langs/shellscript.mjs"),
css: () => import("shiki/langs/css.mjs"),
diff: () => import("shiki/langs/diff.mjs"),
html: () => import("shiki/langs/html.mjs"),
javascript: () => import("shiki/langs/javascript.mjs"),
json: () => import("shiki/langs/json.mjs"),
jsx: () => import("shiki/langs/jsx.mjs"),
markdown: () => import("shiki/langs/markdown.mjs"),
python: () => import("shiki/langs/python.mjs"),
sql: () => import("shiki/langs/sql.mjs"),
tsx: () => import("shiki/langs/tsx.mjs"),
typescript: () => import("shiki/langs/typescript.mjs"),
yaml: () => import("shiki/langs/yaml.mjs"),
}
const aliases: Record<string, keyof typeof languages> = {
js: "javascript",
md: "markdown",
py: "python",
sh: "bash",
shell: "bash",
shellscript: "bash",
ts: "typescript",
yml: "yaml",
zsh: "bash",
}
let highlighter: Promise<HighlighterCore> | undefined
function getHighlighter() {
highlighter ??= createHighlighterCore({
themes: [
import("shiki/themes/github-light.mjs"),
import("shiki/themes/github-dark.mjs"),
],
langs: [],
engine: createJavaScriptRegexEngine({ forgiving: true }),
})
return highlighter
}
function getLanguage(language: string) {
const name = language.toLowerCase()
if (name === "ansi") {
return name
}
if (name in languages) {
return name as keyof typeof languages
}
return aliases[name] ?? null
}
// Loads a language and returns a highlighter for it, or null for a language
// that is not listed.
export async function loadHighlighter(language: string) {
const lang = getLanguage(language)
if (!lang) {
return null
}
const shiki = await getHighlighter()
if (lang !== "ansi" && !shiki.getLoadedLanguages().includes(lang)) {
await shiki.loadLanguage(languages[lang])
}
return {
// Returns one React node per line, and the grammar state after the last
// line. Pass that state back to continue where the code left off.
highlight(code: string, state?: GrammarState) {
const tokenize = (text: string) =>
shiki.codeToTokens(text, {
lang,
themes: { light: "github-light", dark: "github-dark" },
defaultColor: false,
grammarState: state,
}).tokens
// ANSI has no grammar state, so each line is tokenized on its own and
// gets the same colors whether it arrives in one piece or streams.
const tokens =
lang === "ansi"
? code.split("\n").flatMap((line) => tokenize(line))
: tokenize(code)
return {
lines: tokens.map((line) =>
line.map((token, index) => (
<span
key={index}
style={token.htmlStyle as React.CSSProperties}
className="text-(--shiki-light) dark:text-(--shiki-dark)"
>
{token.content}
</span>
))
),
state: shiki.getLastGrammarState(tokens),
}
},
}
}
// Returns one React node per line, or null for a language that is not listed.
export async function highlightCode(code: string, language: string) {
const highlighter = await loadHighlighter(language)
return highlighter ? highlighter.highlight(code).lines : null
}
Update the import paths to match your project setup.
code-block also installs useHighlightedCode for syntax highlighting.
Usage#
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Terminal</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>Composition#
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
│ └── CodeBlockCopyButton
├── CodeBlockActions (floating, when there is no header)
├── CodeBlockContent
│ └── CodeBlockLine
└── CodeBlockFooterCodeBlockContent takes a string or a list of CodeBlockLine. Use lines when you need line variants or highlighted tokens.
Features#
- It streams cheaply. A string child renders as one text node, and the highlighter tokenizes only the new lines as code arrives.
- It copies cleanly. Line numbers and diff markers are left out of a selection, and blank lines survive the copy.
- It reads left to right. The content is always
dir="ltr". The header follows the page direction. - It highlights without WASM.
useHighlightedCodeuses Shiki's JavaScript engine, loads each language on first use and renders ANSI colors in terminal output. On the server,highlightCodekeeps Shiki out of the client bundle. - It fits where code shows up. Use it in a message, a Markdown fence, a Trace line, Tabs, a Dialog or a
typesetcontainer. - It scrolls by keyboard. The content is focusable, and floating actions show on focus as well as on hover.
Basic#
Pass a string to CodeBlockContent. It renders as one text node, so it stays cheap while output streams.
$ 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 kBimport { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output = `$ pnpm buildimport { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output = `$ 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`
export function CodeBlockBasic() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}
Header#
CodeBlockHeader holds a CodeBlockTitle and CodeBlockActions. CodeBlockCopyButton copies its value.
$ 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.0import { TerminalIcon } from "lucide-react"
import {import { TerminalIcon } from "lucide-react"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block"
const command = "pnpm add ai @ai-sdk/react zod"
const output = `$ ${command}
Packages: +14
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0`
export function CodeBlockHeaderExample() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<TerminalIcon />
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={command} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}
A long title truncates. To link the title to a file, wrap CodeBlockTitle in an anchor.
<CodeBlockHeader>
<a href="/files/route.ts">
<CodeBlockTitle>app/api/chat/route.ts</CodeBlockTitle>
</a>
</CodeBlockHeader>Actions#
CodeBlockActions holds any number of buttons. For a wrap toggle, keep the state yourself and pass it to wrap.
$ 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)"use client"
import * as React from "react""use client"
import * as React from "react"
import { DownloadIcon, TerminalIcon, WrapTextIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block"
const output = `$ 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)`
function download(value: string, filename: string) {
const url = URL.createObjectURL(new Blob([value], { type: "text/plain" }))
const link = document.createElement("a")
link.href = url
link.download = filename
link.click()
URL.revokeObjectURL(url)
}
export function CodeBlockActionsExample() {
const [wrap, setWrap] = React.useState(true)
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<TerminalIcon />
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap}
className="aria-pressed:text-foreground"
onClick={() => setWrap(!wrap)}
>
<WrapTextIcon />
</Button>
<Button
variant="ghost"
size="icon-xs"
aria-label="Download"
onClick={() => download(output, "lint.log")}
>
<DownloadIcon />
</Button>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap={wrap}>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}
const [wrap, setWrap] = React.useState(false)
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap}
onClick={() => setWrap(!wrap)}
>
<WrapTextIcon />
</Button>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
<CodeBlockContent wrap={wrap}>{output}</CodeBlockContent>Floating Actions#
Without a header, put CodeBlockActions directly inside CodeBlock. The actions float at the top end and stay hidden until the block is hovered or focused. They always show on touch screens.
$ 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.0import {
CodeBlock,
CodeBlockActions,import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
} from "@/components/ui/code-block"
const output = `$ 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`
export function CodeBlockFloatingActions() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}
Line Numbers#
Add lineNumbers to CodeBlockContent. A string child is split into lines, and the numbers are not copied with a selection.
{ "name": "chat", "private": true, "scripts": { "dev": "next dev", "build": "next build" }}import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const code = `{import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const code = `{
"name": "chat",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build"
}
}`
export function CodeBlockLineNumbers() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockContent lineNumbers>{code}</CodeBlockContent>
</CodeBlock>
</div>
)
}
Start Line#
Set startLine to number lines from a given line, for a snippet from the middle of a file. The gutter grows to fit the widest number.
if (!session) { redirect("/login") }
const projects = await db.project.findMany({ where: { ownerId: session.user.id }, orderBy: { updatedAt: "desc" }, })
return <ProjectList projects={projects} />}"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code""use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const code = ` if (!session) {
redirect("/login")
}
const projects = await db.project.findMany({
where: { ownerId: session.user.id },
orderBy: { updatedAt: "desc" },
})
return <ProjectList projects={projects} />
}`
export function CodeBlockStartLine() {
const lines = useHighlightedCode(code, "tsx")
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>app/dashboard/page.tsx</CodeBlockTitle>
</CodeBlockHeader>
<CodeBlockContent lineNumbers startLine={995}>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
Wrap#
Long lines scroll by default. Add wrap to wrap them, which suits tool output and error messages. To let the reader toggle it, see Actions.
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.import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output = `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.`import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output = `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.`
export function CodeBlockWrap() {
return (
<div className="flex w-full max-w-md flex-col gap-4">
<CodeBlock>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
<CodeBlock>
<CodeBlockContent wrap>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}
Highlighted Lines#
Render each line as a CodeBlockLine and set variant="highlighted" on the lines to call out.
export default { experimental: { reactCompiler: true, viewTransition: true, }, images: { remotePatterns: [{ hostname: "avatars.githubusercontent.com" }], },}import {
CodeBlock,
CodeBlockContent,import {
CodeBlock,
CodeBlockContent,
CodeBlockLine,
} from "@/components/ui/code-block"
const code = `export {
experimental: {
reactCompiler: true,
viewTransition: true,
},
images: {
remotePatterns: [{ hostname: "avatars.githubusercontent.com" }],
},
}`
const highlighted = [2, 3]
export function CodeBlockHighlightedLines() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockContent lineNumbers>
{code.split("\n").map((line, index) => (
<CodeBlockLine
key={index}
variant={highlighted.includes(index) ? "highlighted" : "default"}
>
{line}
</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
Diff#
Set variant="added" or variant="removed" on a CodeBlockLine. Each one adds a + or − marker.
export function Greeting({ name }: { name: string }) { return <p>Hello, {name}</p> return <p className="text-sm text-muted-foreground"> Hello, {name}! </p>}import {
CodeBlock,
CodeBlockActions,import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const patch = ` export function Greeting({ name }: { name: string }) {
- return <p>Hello, {name}</p>
+ return <p className="text-sm text-muted-foreground">
+ Hello, {name}!
+ </p>
}`
function getVariant(line: string) {
if (line.startsWith("+")) {
return "added"
}
if (line.startsWith("-")) {
return "removed"
}
return "default"
}
export function CodeBlockDiff() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>components/greeting.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={patch} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
{patch.split("\n").map((line, index) => (
<CodeBlockLine key={index} variant={getVariant(line)}>
{line.slice(1)}
</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
Height#
Cap the height with a max-h-* class on CodeBlockContent. The content scrolls inside the block.
[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 45msimport {
CodeBlock,
CodeBlockActions,import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block"
const logs = Array.from(
{ length: 40 },
(_, index) =>
`[${String(index + 1).padStart(2, "0")}] GET /api/chat 200 in ${12 + ((index * 7) % 40)}ms`
).join("\n")
export function CodeBlockHeight() {
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Logs</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={logs} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent className="max-h-48 scroll-fade-y">
{logs}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
CodeBlockContent fades its edges with scroll-fade as it scrolls: left and right by default, top and bottom when it wraps. Add scroll-fade-y to a capped block that does not wrap.
Show More#
CodeBlockFooter is a slot below the content. For Show More, cap the content while it is collapsed and put a ghost xs Button in the footer.
"use client" import * as React from "react"import { useChat } from "@ai-sdk/react" import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input" export function Chat() { const [input, setInput] = React.useState("") const { messages, sendMessage, status } = useChat() return ( <div className="flex flex-col gap-4"> {messages.map((message) => ( <div key={message.id}> {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </div> ))} <form onSubmit={(event) => { event.preventDefault() sendMessage({ text: input }) setInput("") }} > <Input value={input} onChange={(event) => setInput(event.target.value)} /> <Button disabled={status !== "ready"}>Send</Button> </form> </div> )}"use client"
import * as React from "react""use client"
import * as React from "react"
import { ChevronDownIcon } from "lucide-react"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import { Button } from "@/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const code = `"use client"
import * as React from "react"
import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
export function Chat() {
const [input, setInput] = React.useState("")
const { messages, sendMessage, status } = useChat()
return (
<div className="flex flex-col gap-4">
{messages.map((message) => (
<div key={message.id}>
{message.parts.map((part, index) =>
part.type === "text" ? <p key={index}>{part.text}</p> : null
)}
</div>
))}
<form
onSubmit={(event) => {
event.preventDefault()
sendMessage({ text: input })
setInput("")
}}
>
<Input value={input} onChange={(event) => setInput(event.target.value)} />
<Button disabled={status !== "ready"}>Send</Button>
</form>
</div>
)
}`
export function CodeBlockShowMore() {
const [expanded, setExpanded] = React.useState(false)
const lines = useHighlightedCode(code, "tsx")
const id = React.useId()
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>components/chat.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent
id={id}
lineNumbers
className={
expanded ? undefined : "max-h-64 scroll-fade-y overflow-y-hidden"
}
>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
<CodeBlockFooter className="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
>
<ChevronDownIcon className="transition-transform in-aria-expanded:rotate-180" />
{expanded ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>
</CodeBlock>
</div>
)
}
const [expanded, setExpanded] = React.useState(false)
const id = React.useId()
<CodeBlockContent
id={id}
className={expanded ? undefined : "max-h-64 overflow-y-hidden scroll-fade-y"}
>
{code}
</CodeBlockContent>
<CodeBlockFooter className="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
>
{expanded ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>Max Height#
To keep a long block from taking over the page, raise the cap instead of removing it. The expanded content scrolls, and the edges fade as you scroll.
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"
export function Chat() { const [input, setInput] = React.useState("") const { messages, sendMessage, status } = useChat()
return ( <div className="flex flex-col gap-4"> {messages.map((message) => ( <div key={message.id}> {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </div> ))} <form onSubmit={(event) => { event.preventDefault() sendMessage({ text: input }) setInput("") }} > <Input value={input} onChange={(event) => setInput(event.target.value)} /> <Button disabled={status !== "ready"}>Send</Button> </form> </div> )}"use client"
import * as React from "react""use client"
import * as React from "react"
import { ChevronDownIcon } from "lucide-react"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import { Button } from "@/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const code = `"use client"
import * as React from "react"
import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
export function Chat() {
const [input, setInput] = React.useState("")
const { messages, sendMessage, status } = useChat()
return (
<div className="flex flex-col gap-4">
{messages.map((message) => (
<div key={message.id}>
{message.parts.map((part, index) =>
part.type === "text" ? <p key={index}>{part.text}</p> : null
)}
</div>
))}
<form
onSubmit={(event) => {
event.preventDefault()
sendMessage({ text: input })
setInput("")
}}
>
<Input value={input} onChange={(event) => setInput(event.target.value)} />
<Button disabled={status !== "ready"}>Send</Button>
</form>
</div>
)
}`
export function CodeBlockShowMoreScroll() {
const [expanded, setExpanded] = React.useState(false)
const lines = useHighlightedCode(code, "tsx")
const id = React.useId()
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>components/chat.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent
id={id}
lineNumbers
className={
expanded
? "max-h-96 scroll-fade-y"
: "max-h-64 scroll-fade-y overflow-y-hidden"
}
>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
<CodeBlockFooter className="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
>
<ChevronDownIcon className="transition-transform in-aria-expanded:rotate-180" />
{expanded ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>
</CodeBlock>
</div>
)
}
Size#
Use size="sm" for tool and Trace output. It has tighter padding and text-xs text.
$ 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$ 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.0import { TerminalIcon } from "lucide-react"
import {import { TerminalIcon } from "lucide-react"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block"
const output = `$ 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`
export function CodeBlockSize() {
return (
<div className="flex w-full max-w-md flex-col gap-4">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<TerminalIcon />
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>{output}</CodeBlockContent>
</CodeBlock>
<CodeBlock size="sm">
<CodeBlockHeader>
<CodeBlockTitle>
<TerminalIcon />
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}
Destructive#
Use variant="destructive" for errors and failed output.
TypeError: Cannot read properties of undefined (reading 'map')
at MessageList (components/message-list.tsx:18:22)
at renderWithHooks (react-dom.development.js:16305:18)import {
CodeBlock,
CodeBlockActions,import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block"
const 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)`
export function CodeBlockDestructive() {
return (
<div className="w-full max-w-md">
<CodeBlock variant="destructive">
<CodeBlockHeader>
<CodeBlockTitle>Error</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={error} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>{error}</CodeBlockContent>
</CodeBlock>
</div>
)
}
Trace#
Put a CodeBlock with size="sm" in TraceCollapsibleContent for tool and terminal output. Add wrap and a max-h-64 class to CodeBlockContent so long output wraps and scrolls inside the trace. The block sets its own text color, so TraceCollapsibleContent does not mute it.
$ node --version
v24.18.0$ pnpm dev
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1908:16)import { TerminalIcon } from "lucide-react"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { TerminalIcon } from "lucide-react"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace"
const output = `$ node --version
v24.18.0`
const error = `$ pnpm dev
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1908:16)`
export function CodeBlockTrace() {
return (
<div className="w-full max-w-md">
<Trace>
<TraceCollapsible defaultOpen>
<TraceCollapsibleTrigger>
<TraceLine>
<TraceIcon>
<TerminalIcon />
</TraceIcon>
<TraceTitle>Ran node --version</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<CodeBlock size="sm">
<CodeBlockContent wrap className="max-h-64">
{output}
</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
<TraceCollapsible defaultOpen>
<TraceCollapsibleTrigger>
<TraceLine status="error">
<TraceIcon>
<TerminalIcon />
</TraceIcon>
<TraceTitle>Failed to run pnpm dev</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<CodeBlock size="sm" variant="destructive">
<CodeBlockContent wrap className="max-h-64">
{error}
</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</div>
)
}
Tabs#
Show several files with Tabs, one CodeBlock in each TabsContent.
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json() const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()}"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() { const { messages } = useChat()
return <MessageList messages={messages} />}AI_GATEWAY_API_KEY=your-api-key"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code""use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from "@/components/ui/tabs"
const files = [
{
id: "route",
title: "app/api/chat/route.ts",
language: "ts",
code: `import { streamText } from "ai"
export async function POST(request: Request) {
const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()
}`,
},
{
id: "chat",
title: "components/chat.tsx",
language: "tsx",
code: `"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() {
const { messages } = useChat()
return <MessageList messages={messages} />
}`,
},
{
id: "env",
title: ".env.local",
language: "bash",
code: "AI_GATEWAY_API_KEY=your-api-key",
},
]
function FileCode({ code, language }: { code: string; language: string }) {
const lines = useHighlightedCode(code, language)
return (
<CodeBlockContent lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
)
}
export function CodeBlockTabs() {
return (
<Tabs defaultValue="route" className="w-full max-w-md">
<TabsList>
{files.map((file) => (
<TabsTrigger key={file.id} value={file.id}>
{file.title.split("/").at(-1)}
</TabsTrigger>
))}
</TabsList>
{files.map((file) => (
<TabsContent key={file.id} value={file.id}>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>{file.title}</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={file.code} />
</CodeBlockActions>
</CodeBlockHeader>
<FileCode code={file.code} language={file.language} />
</CodeBlock>
</TabsContent>
))}
</Tabs>
)
}
Message#
Put a CodeBlock between paragraphs inside a Message.
Create a route handler that returns the stream:
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, })
return result.toUIMessageStreamResponse()}The client reads it with useChat.
"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code""use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
import { Message, MessageContent } from "@/components/ui/message"
const code = `import { streamText } from "ai"
export async function POST(request: Request) {
const { messages } = await request.json()
const result = streamText({
model: "anthropic/claude-sonnet-4.5",
messages,
})
return result.toUIMessageStreamResponse()
}`
export function CodeBlockChat() {
const lines = useHighlightedCode(code, "ts")
return (
<div className="flex w-full max-w-md flex-col gap-4 text-sm">
<Message align="end">
<MessageContent>
<Bubble variant="muted">
<BubbleContent>How do I stream a response?</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message>
<MessageContent className="gap-3">
<p>Create a route handler that returns the stream:</p>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>app/api/chat/route.ts</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
<p>The client reads it with useChat.</p>
</MessageContent>
</Message>
</div>
)
}
Typeset#
A CodeBlock inside a typeset container keeps its own styles and gets the same space above as a paragraph.
Stream a response
Create a route handler that calls streamText and returns the stream to the client.
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json() const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()}The useChat hook reads the stream on the client and renders the answer while it is written.
"use client"
import { FileCodeIcon } from "lucide-react""use client"
import { FileCodeIcon } from "lucide-react"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const code = `import { streamText } from "ai"
export async function POST(request: Request) {
const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()
}`
export function CodeBlockTypeset() {
const lines = useHighlightedCode(code, "ts")
return (
<div className="typeset w-full max-w-md">
<h3>Stream a response</h3>
<p>
Create a route handler that calls <code>streamText</code> and returns
the stream to the client.
</p>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<FileCodeIcon />
app/api/chat/route.ts
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
<p>
The <code>useChat</code> hook reads the stream on the client and renders
the answer while it is written.
</p>
</div>
)
}
RTL#
To enable RTL support in shadcn/ui, see the RTL configuration guide. Code always reads left to right. The header follows the page direction.
ثبّت الحزم، ثم شغّل خادم التطوير.
pnpm add ai @ai-sdk/react zodpnpm dev"use client"
import { TerminalIcon } from "lucide-react"// You will notice this example uses dir and data-lang attributes. // This is because this site is not RTL by default. // In your application, you won't need these.// See the RTL guide for more information.
"use client"
import { TerminalIcon } from "lucide-react"
import {
useTranslation,
type Translations,
} from "@/components/language-selector"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const translations: Translations = {
en: {
dir: "ltr",
values: {
description: "Install the packages, then start the dev server.",
title: "Terminal",
},
},
ar: {
dir: "rtl",
values: {
description: "ثبّت الحزم، ثم شغّل خادم التطوير.",
title: "الطرفية",
},
},
he: {
dir: "rtl",
values: {
description: "התקן את החבילות, ואז הפעל את שרת הפיתוח.",
title: "מסוף",
},
},
}
const code = `pnpm add ai @ai-sdk/react zod
pnpm dev`
export function CodeBlockRtl() {
const { dir, t } = useTranslation(translations, "ar")
const lines = useHighlightedCode(code, "bash")
return (
<div className="flex w-full max-w-md flex-col gap-3 text-sm" dir={dir}>
<p>{t.description}</p>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<TerminalIcon />
{t.title}
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
Syntax Highlighting#
useHighlightedCode highlights with Shiki and returns one React node per line for CodeBlockLine.
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code""use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const code = `{
"location": "San Francisco",
"temperature": 18,
"unit": "celsius",
"conditions": ["fog", "wind"]
}`
export function CodeBlockHighlighting() {
const lines = useHighlightedCode(code, "json")
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>getWeather output</CodeBlockTitle>
</CodeBlockHeader>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
const lines = useHighlightedCode(code, "json")
<CodeBlock>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>Shiki uses its JavaScript regex engine, so there is no WASM to load.
Languages#
Each language loads the first time it is used. Edit the list in lib/highlighter.tsx. A language that is not in the list renders as plain text.
@import "tailwindcss";
:root { --radius: 0.625rem;}def greet(name: str) -> str: return f"Hello, {name}!"A language that is not in the list renders as plain text."use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code""use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const samples = [
{
language: "css",
title: "app/globals.css",
code: `@import "tailwindcss";
:root {
--radius: 0.625rem;
}`,
},
{
language: "python",
title: "main.py",
code: `def greet(name: str) -> str:
return f"Hello, {name}!"`,
},
{
language: "text",
title: "notes.txt",
code: "A language that is not in the list renders as plain text.",
},
]
function Sample({ code, language }: { code: string; language: string }) {
const lines = useHighlightedCode(code, language)
return (
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
)
}
export function CodeBlockLanguages() {
return (
<div className="flex w-full max-w-md flex-col gap-4">
{samples.map((sample) => (
<CodeBlock key={sample.language}>
<CodeBlockHeader>
<CodeBlockTitle>{sample.title}</CodeBlockTitle>
</CodeBlockHeader>
<Sample code={sample.code} language={sample.language} />
</CodeBlock>
))}
</div>
)
}
The list ships with bash, css, diff, html, javascript, json, jsx, markdown, python, sql, tsx, typescript and yaml, plus aliases such as ts, js, sh and yml.
Terminal Output#
Pass "ansi" as the language to render the colors in terminal output. Without it, escape codes show as text.
$ pnpm test✓ src/format.test.ts (4 tests)✓ src/parse.test.ts (7 tests)✗ src/stream.test.ts (3 tests | 1 failed)
AssertionError: expected 'hello' to be 'hello world'
Tests 1 failed | 13 passed (14)"use client"
import { TerminalIcon } from "lucide-react""use client"
import { TerminalIcon } from "lucide-react"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const output = `$ pnpm test
\x1b[32m✓\x1b[39m src/format.test.ts \x1b[2m(4 tests)\x1b[22m
\x1b[32m✓\x1b[39m src/parse.test.ts \x1b[2m(7 tests)\x1b[22m
\x1b[31m✗\x1b[39m src/stream.test.ts \x1b[2m(3 tests | 1 failed)\x1b[22m
\x1b[31mAssertionError: expected 'hello' to be 'hello world'\x1b[39m
Tests \x1b[31m1 failed\x1b[39m | \x1b[32m13 passed\x1b[39m (14)`
export function CodeBlockAnsi() {
const lines = useHighlightedCode(output, "ansi")
return (
<div className="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<TerminalIcon />
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output.replace(/\x1b\[[\d;]*m/g, "")} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
</div>
)
}
ANSI colors do not carry from one line to the next.
Server Rendering#
highlightCode is async and works in a Server Component, so Shiki stays out of the client bundle.
import { highlightCode } from "@/lib/highlighter"
export async function ServerCode({ code }: { code: string }) {
const lines = (await highlightCode(code, "tsx")) ?? code.split("\n")
return (
<CodeBlock>
<CodeBlockContent lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
)
}Streaming#
While the code streams, the hook tokenizes only the new lines, starting where the last line left off. Lines that did not change keep the same nodes, so React skips them.
export function useDebounce<T>(value: T, delay = 300) { const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => { const timeout = setTimeout(() => setDebounced(value), delay) return () => clearTimeout(timeout) }, [value, delay])
return debounced}pnpm dlx shadcn@latest add code-blockexport function Search() { const [query, setQuery] = React.useState("") const results = useSearch(query) const debounced = useDebounce(query, 300) const results = useSearch(debounced)
return <SearchResults results={results} />}import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, })
return result.toUIMessageStreamResponse()}AI_GATEWAY_API_KEY=your-api-key"use client"
import * as React from "react""use client"
import * as React from "react"
import { RotateCcwIcon } from "lucide-react"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import { Button } from "@/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
const blocks: {
title?: string
language: string
code: string
lineNumbers?: boolean
highlight?: number[]
diff?: boolean
}[] = [
{
title: "hooks/use-debounce.ts",
language: "ts",
lineNumbers: true,
code: `export function useDebounce<T>(value: T, delay = 300) {
const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => {
const timeout = setTimeout(() => setDebounced(value), delay)
return () => clearTimeout(timeout)
}, [value, delay])
return debounced
}`,
},
{
language: "bash",
code: "pnpm dlx shadcn@latest add code-block",
},
{
title: "components/search.tsx",
language: "tsx",
lineNumbers: true,
diff: true,
code: ` export function Search() {
const [query, setQuery] = React.useState("")
- const results = useSearch(query)
+ const debounced = useDebounce(query, 300)
+ const results = useSearch(debounced)
return <SearchResults results={results} />
}`,
},
{
title: "app/api/chat/route.ts",
language: "ts",
lineNumbers: true,
highlight: [5, 6, 7, 8],
code: `import { streamText } from "ai"
export async function POST(request: Request) {
const { messages } = await request.json()
const result = streamText({
model: "anthropic/claude-sonnet-4.5",
messages,
})
return result.toUIMessageStreamResponse()
}`,
},
{
title: ".env.local",
language: "bash",
code: "AI_GATEWAY_API_KEY=your-api-key",
},
]
// Where each block starts in the stream.
const offsets = blocks.map((_, index) =>
blocks.slice(0, index).reduce((total, block) => total + block.code.length, 0)
)
const total = blocks.reduce((sum, block) => sum + block.code.length, 0)
function StreamingBlock({
block,
code,
}: {
block: (typeof blocks)[number]
code: string
}) {
const rows = code.split("\n")
// A diff row starts with +, - or a space. The marker is not part of the code.
const source = block.diff ? rows.map((row) => row.slice(1)).join("\n") : code
const lines = useHighlightedCode(source, block.language)
return (
<CodeBlock>
{block.title && (
<CodeBlockHeader>
<CodeBlockTitle>{block.title}</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton
value={source}
disabled={code.length < block.code.length}
/>
</CodeBlockActions>
</CodeBlockHeader>
)}
<CodeBlockContent lineNumbers={block.lineNumbers}>
{lines.map((line, index) => (
<CodeBlockLine
key={index}
variant={
block.diff
? rows[index]?.startsWith("+")
? "added"
: rows[index]?.startsWith("-")
? "removed"
: "default"
: block.highlight?.includes(index)
? "highlighted"
: "default"
}
>
{line}
</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
)
}
export function CodeBlockStreaming() {
const [length, setLength] = React.useState(total)
React.useEffect(() => {
if (length >= total) {
return
}
const timeout = setTimeout(() => setLength(length + 3), 16)
return () => clearTimeout(timeout)
}, [length])
return (
<div className="flex w-full max-w-md flex-col gap-4">
{blocks.map(
(block, index) =>
length > offsets[index] && (
<StreamingBlock
key={block.code}
block={block}
code={block.code.slice(0, length - offsets[index])}
/>
)
)}
<Button
variant="outline"
size="sm"
className="self-start"
disabled={length < total}
onClick={() => setLength(0)}
>
<RotateCcwIcon />
Replay
</Button>
</div>
)
}
Markdown#
Render the message with Streamdown and route fenced code to a CodeBlock with components.code. Streamdown sets data-block on fenced code only, so inline code stays inline.
Wrap the value in a useDebounce hook. It returns the latest value once it stops changing for delay milliseconds.
export function useDebounce<T>(value: T, delay = 300) { const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => { const timeout = setTimeout(() => setDebounced(value), delay) return () => clearTimeout(timeout) }, [value, delay])
return debounced}Pass the debounced value to your fetch instead of the raw input.
"use client"
import * as React from "react""use client"
import * as React from "react"
import { useChat } from "@ai-sdk/react"
import {
Streamdown,
useIsCodeFenceIncomplete,
type ExtraProps,
} from "streamdown"
import { createChat, getMessageText } from "@/lib/ai"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
import { Bubble, BubbleContent } from "@/components/ui/bubble"
import { Button } from "@/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"
import { Message, MessageContent } from "@/components/ui/message"
const response = `Wrap the value in a \`useDebounce\` hook. It returns the latest value once it stops changing for \`delay\` milliseconds.
\`\`\`tsx
export function useDebounce<T>(value: T, delay = 300) {
const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => {
const timeout = setTimeout(() => setDebounced(value), delay)
return () => clearTimeout(timeout)
}, [value, delay])
return debounced
}
\`\`\`
Pass the debounced value to your fetch instead of the raw input.`
const chat = createChat()
.user("How do I debounce a search input in React?")
.assistant(({ writer }) => {
writer.text(response)
})
const transcript = chat.get()
const [question] = chat.get(1)
const transport = chat.transport({ delayMs: 30 })
function MarkdownCodeBlock({
code,
language,
}: {
code: string
language: string
}) {
// True while the closing fence has not arrived yet.
const incomplete = useIsCodeFenceIncomplete()
const lines = useHighlightedCode(code, language)
return (
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>{language || "text"}</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} disabled={incomplete} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
)
}
function MarkdownCode({
node,
className,
children,
...props
}: React.ComponentProps<"code"> & ExtraProps) {
// Streamdown marks fenced code with data-block. Everything else is inline.
if (!("data-block" in props)) {
return (
<code
className="rounded-sm bg-muted px-1 py-0.5 font-mono text-[0.9em]"
{...props}
>
{children}
</code>
)
}
return (
<MarkdownCodeBlock
code={typeof children === "string" ? children : ""}
language={/language-(\S+)/.exec(className ?? "")?.[1] ?? ""}
/>
)
}
const components = { code: MarkdownCode }
export function CodeBlockMarkdown() {
const { messages, sendMessage, setMessages, status } = useChat({
messages: transcript,
transport,
})
const busy = status === "submitted" || status === "streaming"
return (
<div className="flex min-h-112 w-full max-w-md flex-col gap-4 py-6 text-sm">
{messages.map((message) =>
message.role === "user" ? (
<Message key={message.id} align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{getMessageText(message)}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
) : (
<Message key={message.id}>
<MessageContent>
<Streamdown
controls={false}
components={components}
isAnimating={busy && message === messages.at(-1)}
>
{getMessageText(message)}
</Streamdown>
</MessageContent>
</Message>
)
)}
{!busy && (
<Button
variant="outline"
size="sm"
className="mt-auto self-start"
onClick={() => {
setMessages([])
sendMessage(question)
}}
>
Replay
</Button>
)}
</div>
)
}
useIsCodeFenceIncomplete returns true until the closing fence arrives. Use it to disable the copy button while the code is incomplete. It only works when Streamdown gets isAnimating, so pass isAnimating while the message streams.
<Streamdown components={{ code: MarkdownCode }} isAnimating={isStreaming}>
{text}
</Streamdown>Accessibility#
CodeBlockContentis aprewith acodeelement and always setsdir="ltr", so code reads left to right on an RTL page.CodeBlockContenthastabIndex={0}, so keyboard users can focus it and scroll it. PasstabIndex={-1}to remove the tab stop.- Floating actions show when focus is inside the block, not only on hover, so keyboard users can reach them.
- Line numbers are hidden from screen readers.
- Diff lines carry a
+or−marker as well as a tint, so the change does not rely on color. CodeBlockCopyButtonis labelled "Copy", and a polite live region announces "Copied" after a successful copy.- Give a wrap toggle
aria-pressedso its state is announced. - Give a Show More button
aria-expandedand pointaria-controlsat theidofCodeBlockContent.
API Reference#
CodeBlock#
The surface that holds the header, the content and the footer.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "destructive" | "default" | The tone of the block. |
size | "default" | "sm" | "default" | "sm" has tighter padding and text-xs code, for tool output. |
className | string | - | Additional classes to apply to the block. |
CodeBlockHeader#
A row above the content for a title and actions.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the header. |
CodeBlockTitle#
A filename or a label, with an optional icon. It truncates.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the title. |
CodeBlockActions#
Holds buttons at the end of the header. As a direct child of CodeBlock, it floats.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the actions. |
CodeBlockCopyButton#
A ghost icon button that copies value to the clipboard. It accepts the props of Button.
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | - | Required. The text to copy. |
className | string | - | Additional classes to apply to the button. |
CodeBlockContent#
The pre that scrolls or wraps.
| Prop | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | - | A string, or a list of CodeBlockLine. |
wrap | boolean | false | Wrap long lines instead of scrolling. |
lineNumbers | boolean | false | Number each line. A string child is split into lines. |
startLine | number | 1 | The number of the first line, when lineNumbers is set. |
tabIndex | number | 0 | Makes the content focusable so it can be scrolled by keyboard. |
className | string | - | Additional classes to apply to the content, such as max-h-72. |
CodeBlockLine#
One line of code.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "added" | "removed" | "highlighted" | "default" | The state of the line. |
className | string | - | Additional classes to apply to the line. |
CodeBlockFooter#
A row below the content, such as for a Show More button.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the footer. |
useHighlightedCode#
const lines = useHighlightedCode(code, language)Returns one React node per line. It returns plain lines until the first pass finishes, and for a language that is not in the list.
| Argument | Type | Description |
|---|---|---|
code | string | The code to highlight. A trailing newline is ignored. |
language | string | A language or alias from lib/highlighter.tsx, or "ansi". |
On This Page
InstallationUsageCompositionFeaturesBasicHeaderActionsFloating ActionsLine NumbersStart LineWrapHighlighted LinesDiffHeightShow MoreMax HeightSizeDestructiveTraceTabsMessageTypesetRTLSyntax HighlightingLanguagesTerminal OutputServer RenderingStreamingMarkdownAccessibilityAPI ReferenceCodeBlockCodeBlockHeaderCodeBlockTitleCodeBlockActionsCodeBlockCopyButtonCodeBlockContentCodeBlockLineCodeBlockFooteruseHighlightedCode