Sandpack Documentation

repository·main·Indexed 27 days ago

https://github.com/codesandbox/sandpack

A component toolkit for creating live, running code editing experiences powered by CodeSandbox. It includes @codesandbox/sandpack-react for React components, @codesandbox/sandpack-client for framework-agnostic initialization via loadSandpackClient, and @codesandbox/sandpack-themes for visual customization. The toolkit supports various environments through specialized clients: SandpackRuntime for browser-based runtimes, SandpackNode for Node.js environments, and SandpackStatic for static file serving.

Tokens
32.8K
Snippets
92
Records
176
Agent score
91%

What's inside Sandpack

  1. Introduction to Sandpack

    main

    Sandpack is a component toolkit designed for creating live-running code editing experiences. It is powered by the same online bundler used by CodeSandbox, allowing you to compile and run modern JavaScript and Node.js frameworks directly in the browser.

    Developers can use Sandpack in two primary ways:

    1. Predefined Components: Use existing components to embed a full CodeSandbox-like experience into your project.
    2. Custom Implementation: Build a custom version of Sandpack by using the provided standard components and utilities as building blocks.
  2. Overview of Nodebox Runtime

    main

    Nodebox is a runtime that executes Node.js code directly in the browser. It is a core building block of Sandpack 2.0 used to run server-side examples (like Vite-based React or Vue templates) on a website.

    Key Characteristics:

    • Compatibility: Aims for Node.js@18 compatibility by polyfilling standard APIs like fs and net.
    • Connectivity: Requires an initial network connection to download node modules from https://sandpack-cdn-v2.codesandbox.io and load preview domains from https://id-port.nodebox.codesandbox.io. Once loaded, it works offline.
    • Standalone Use: Nodebox is available as a standalone package on npm, independent of Sandpack.
    • Browser Support: Works on latest WebKit (Safari/iOS), Blink (Chrome/Edge/Brave), and Gecko (Firefox) browsers.
    • Limitations: Does not support native Node modules (unless they have a WASM version), native sockets (e.g., direct Postgres/MySQL connections), or synchronous cross-process communication.
  3. Overview of Sandpack packages

    main

    Sandpack is composed of several specialized packages depending on your needs:

    • @codesandbox/sandpack-client: A framework-agnostic foundation package that facilitates the handshake between your application context and the bundler iframe.
    • @codesandbox/sandpack-react: A collection of React components for building editable browser-based sandboxes.
    • @codesandbox/sandpack-themes: A library of pre-defined themes for customizing Sandpack component styles.
  4. Authentication flow for private dependencies

    main

    To access private packages, Sandpack follows a specific authentication and configuration flow:

    1. Authentication: The Sandpack component initiates authentication by redirecting the user to codesandbox.io/auth/sandpack?team-id=<team-id>. The CodeSandbox authentication service verifies the team-id and issues a sandpack-secret token, which is stored in a secure cookie (SameSite=None; Secure=true).
    2. Trusted Domains: Sandpack requests the list of trusted domains for the team-id from the CodeSandbox API. This list is used to configure the appropriate Content Security Policy (CSP) frame-ancestors headers for the iframe.
    3. Package Fetching: Sandpack uses the sandpack-secret token to request private package data from the CodeSandbox API. The API authenticates the request and retrieves the payload from the internal npm registry, handling token renewal automatically.
  5. Understand the Sandpack Architecture

    main

    Sandpack operates through three primary layers that work together to provide a live code editing experience:

    1. Sandpack React: The entry point for React applications. The <Sandpack /> component initializes the environment and manages the React integration and UI state.
    2. Sandpack Client: The core logic layer. The loadSandpackClient() function selects the appropriate client type (VM, Runtime, Static, or Node) based on the provided files, template, and dependencies. It creates the sandbox context and returns a new client instance.
    3. Bundler: The processing layer. It handles the sandbox setup and code bundling, sending updates back to the client to keep the environment in sync.
  6. Integrate Monaco Editor with Sandpack

    main

    You can replace the default Sandpack code editor with Monaco Editor by creating a custom component that uses Sandpack hooks like useActiveCode and useSandpack.

    To ensure the editor updates correctly when switching files, pass sandpack.activeFile to the key prop of the Monaco Editor component. Use the onChange callback to sync the editor content back to Sandpack via updateCode.

    import Editor from "@monaco-editor/react";
    import {
      useActiveCode,
      SandpackStack,
      FileTabs,
      useSandpack,
    } from "@codesandbox/sandpack-react";
    
    function MonacoEditor() {
      const { code, updateCode } = useActiveCode();
      const { sandpack } = useSandpack();
    
      return (
        <SandpackStack style={{ height: "100vh", margin: 0 }}>
          <FileTabs />
          <div style={{ flex: 1, paddingTop: 8, background: "#1e1e1e" }}>
            <Editor
              width="100%"
              height="100%"
              language="javascript"
              theme="vs-dark"
              key={sandpack.activeFile}
              defaultValue={code}
              onChange={(value) => updateCode(value || "")}
            />
          </div>
        </SandpackStack>
      );
    }
  7. Rebuild Sandpack presets using Sandpack components

    main

    You can build custom Sandpack layouts by using individual components from the @codesandbox/sandpack-react package instead of the high-level <Sandpack /> component. These components must be wrapped within a <SandpackProvider /> to function. This allows you to control the layout, swap component positions, and pass specific props to individual parts of the editor experience.

    import {
      SandpackProvider,
      SandpackLayout,
      SandpackCodeEditor,
      SandpackPreview,
    } from "@codesandbox/sandpack-react";
    
    export default () => (
      <SandpackProvider template="react">
        <SandpackLayout>
          <SandpackCodeEditor />
          <SandpackPreview />
        </SandpackLayout>
      </SandpackProvider>
    );
  8. Configure SSR in Gatsby

    main

    In Gatsby, use the onRenderBody API in your gatsby-ssr.js file to add the Sandpack styles to the head components.

    // gatsby-ssr.js
    import * as React from "react";
    import { getSandpackCssText } from "@codesandbox/sandpack-react";
    
    export const onRenderBody = ({ setHeadComponents }) => {
      setHeadComponents([
        <style
          id="sandpack"
          key="sandpack-css"
          dangerouslySetInnerHTML={{
            __html: getSandpackCssText(),
          }}
        />,
      ]);
    };
  9. Run tests in the browser with SandpackTests

    main

    The SandpackTests component provides a thin wrapper around Jest to run tests directly in the browser. It automatically detects and runs test files ending with .test.js(x), .spec.js(x), .test.ts(x), and .spec.ts(x).

    To use it, you can either use the test-ts template preset or use the standalone SandpackTests component within a SandpackLayout for more control.

    import { 
      SandpackProvider, 
      SandpackLayout, 
      SandpackCodeEditor, 
      SandpackTests 
    } from "@codesandbox/sandpack-react";
    
    export default () => (
      <SandpackProvider template="test-ts">
        <SandpackLayout>
          <SandpackTests />
          <SandpackCodeEditor />
        </SandpackLayout>
      </SandpackProvider>
    );
  10. Hide test files and logs in Sandpack

    main

    To suppress test files from the file explorer, use the visibleFiles prop in SandpackProvider. To hide test content and suppress console logs entirely, use the hideTestsAndSupressLogs prop on the SandpackTests component.

    import {
      SandpackProvider,
      SandpackLayout,
      SandpackCodeEditor,
      SandpackTests,
    } from "@codesandbox/sandpack-react";
    
    export default () => (
      <SandpackProvider
        template="test-ts"
        options={{
          activeFile: "/add.ts",
          visibleFiles: ["/add.ts"],
        }}
      >
        <SandpackLayout>
          <SandpackCodeEditor />
          <SandpackTests hideTestsAndSupressLogs />
        </SandpackLayout>
      </SandpackProvider>
    );