📄 ai-sdk/elements/components/code-block

File: code-block.md | Updated: 11/15/2025

Source: https://ai-sdk.dev/elements/components/code-block

Vercel

Slash Forward

Sparkles

AI SDK

Docs Cookbook Providers Playground AI ElementsAI ElementsLeft sparkleRight sparkle AI GatewayGateway

Search...⌘KFeedback GitHub Vercel LogoSign in with Vercel

Utilities

Code Block

Provides syntax highlighting, line numbers, and copy to clipboard functionality for code blocks.

The CodeBlock component provides syntax highlighting, line numbers, and copy to clipboard functionality for code blocks.

Preview

Code

Installation


AI Elements

shadcn CLI

Manual

npx ai-elements@latest add code-block

Usage with AI SDK


Build a simple code generation tool using the experimental_useObject hook.

Add the following component to your frontend:

app/page.tsx

'use client';

import { experimental_useObject as useObject } from '@ai-sdk/react';
import { codeBlockSchema } from '@/app/api/codegen/route';
import {
  Input,
  PromptInputTextarea,
  PromptInputSubmit,
} from '@/components/ai-elements/prompt-input';
import {
  CodeBlock,
  CodeBlockCopyButton,
} from '@/components/ai-elements/code-block';
import { useState } from 'react';

export default function Page() {
  const [input, setInput] = useState('');
  const { object, submit, isLoading } = useObject({
    api: '/api/codegen',
    schema: codeBlockSchema,
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (input.trim()) {
      submit(input);
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]">
      <div className="flex flex-col h-full">
        <div className="flex-1 overflow-auto mb-4">
          {object?.code && object?.language && (
            <CodeBlock
              code={object.code}
              language={object.language}
              showLineNumbers={true}
            >
              <CodeBlockCopyButton />
            </CodeBlock>
          )}
        </div>

        <Input
          onSubmit={handleSubmit}
          className="mt-4 w-full max-w-2xl mx-auto relative"
        >
          <PromptInputTextarea
            value={input}
            placeholder="Generate a React todolist component"
            onChange={(e) => setInput(e.currentTarget.value)}
            className="pr-12"
          />
          <PromptInputSubmit
            status={isLoading ? 'streaming' : 'ready'}
            disabled={!input.trim()}
            className="absolute bottom-1 right-1"
          />
        </Input>
      </div>
    </div>
  );
}

Add the following route to your backend:

api/codegen/route.ts

import { streamObject } from 'ai';
import { z } from 'zod';

export const codeBlockSchema = z.object({
  language: z.string(),
  filename: z.string(),
  code: z.string(),
});
// Allow streaming responses up to 30 seconds
export const maxDuration = 30;

export async function POST(req: Request) {
  const context = await req.json();

  const result = streamObject({
    model: 'openai/gpt-4o',
    schema: codeBlockSchema,
    prompt:
      `You are a helpful coding assistant. Only generate code, no markdown formatting or backticks, or text.` +
      context,
  });

  return result.toTextStreamResponse();
}

Features


  • Syntax highlighting with shiki
  • Line numbers (optional)
  • Copy to clipboard functionality
  • Automatic light/dark theme switching
  • Customizable styles
  • Accessible design

Examples


Dark Mode

To use the CodeBlock component in dark mode, you can wrap it in a div with the dark class.

Preview

Code

Props


<CodeBlock />

Prop

Type

code?string

language?string

showLineNumbers?boolean

children?React.ReactNode

className?string

...props?React.HTMLAttributes<HTMLDivElement>

<CodeBlockCopyButton />

Prop

Type

onCopy?() => void

onError?(error: Error) => void

timeout?number

children?React.ReactNode

className?string

...props?React.ComponentProps<typeof Button>

Open In Chat

A dropdown menu for opening queries in various AI chat platforms including ChatGPT, Claude, T3, Scira, and v0.
Image

Displays AI-generated images from the AI SDK.

On this page

Installation Usage with AI SDK Features Examples Dark Mode Props <CodeBlock /> <CodeBlockCopyButton />

GitHubEdit this page on GitHub Scroll to topCopy pageOpen in chat