SDK
Previews

Previews

The previews API allows you to create and interact with previews in the browser. You can navigate, listen to messages and even inject custom code into the preview.

API

import { connectToSandbox, createPreview } from '@codesandbox/sdk/browser'
 
const client = await connectToSandbox({
    session: initialSessionFromServer,
    getSession: (id) => fetchJson(`/api/sandboxes/${id}`))
})
 
// We have a dev server running on port 5173
const preview = createPreview(client.hosts.getUrl(5173))
 
document.querySelector('#preview-container').appendChild(preview.iframe)
💡

If you are running public previews you can also just use the port url directly without a preview token.

Messages

You can listen to messages from the preview:

preview.onMessage((message) => {
    switch (message.type) {
        case 'SET_URL': {
            // Url that was set
            message.url
            // If you can move backward
            message.back
            // If you can move forward
            message.forward
            break;
        }
        case 'RELOAD': {
            // If preview reloaded
        }
        case 'PREVIEW_UNLOADING': {
            // Preview will unload
        }
    }
})
💡

By injecting your own code you can extend these messages to your own.

Navigate

// Replace the current url
preview.setUrl("...")
 
// Navigate back
preview.back()
 
// Navigate forward
preview.forward()
 
// Reload the iframe
preview.reload()

Inject and Invoke

You can inject any code into the preview. This is useful if you want to insert custom UI elements, background processes.etc The injected code can listen to messages, send messages and has access to any variables (scope) you send to the injected code.

preview.onMessage((message) => {
    console.log(message)
})
 
preview.injectAndInvoke(function MyInjectedFunction({ previewProtocol, previewWindow, scope }) {
    alert(scope.message)
    previewProtocol.sendMessage({ type: 'ALERTED' })
}, {
    message: 'Hello World'
})
💡

Note that the function passed to injectAndInvoke will be stringified and sent to the preview. Be careful about your build tool transforming this function into invalid code.

Initial loading state with waitForPort

When you create a preview for a development server, the iframe may load before the server is ready, resulting in a blank or error page. You can use the Ports API to wait until the preview port is open before attaching the iframe.

// Wait for the preview port (e.g., 5173) to become available
const portInfo = await client.ports.waitForPort(5173)
 
// Create the preview using the resolved host URL
const preview = createPreview(portInfo.host)
 
document.querySelector('#preview-container').appendChild(preview.iframe)

The waitForPort method resolves once the sandbox has opened the specified port, ensuring the preview iframe points to a live server. For more details about the Ports API, see the Ports documentation.