sandpack icon indicating copy to clipboard operation
sandpack copied to clipboard

PNG Static Assets

Open dariuscosden opened this issue 4 months ago • 1 comments

The documentation shows how to import a static SVG file, however I am not able to get it working with a PNG file.

I am not sure what format I need to provide the image in. I have tried raw bytes, base64, and am not getting any results.

Please advise and ideally update the documentation to show how to handle different kinds of file formats for static assets if they require different data.

<Sandpack
    files={{
      "/public/image.png": "", // What do I provide here?
      "/App.js": `export default function App() {
  return (
    <>
      <h1>Hello React</h1>
      <img width="100" src="/public/image.png" />
    </>
  );
}
      `,
    }}
    options={{
      experimental_enableServiceWorker: true,
    }}
    template="react"
  />

dariuscosden avatar Sep 05 '25 12:09 dariuscosden

I have a similar issue, but with a JPEG. I was setting my file path to binary data. The response from the Sandpack url is returning a 200, but the issue is the Service Worker is returning Content-Type: text/html, not Content-Type: image/jpeg. I am not sure we are going to fix it as this appears to be a Sandpack limitation/bug.

As a test, I was doing the minimal. My example, which DID NOT work:

const [data, setData] = useState<string | null>(null);

useEffect(() => {
 (async () => {
  const res = await fetch(parrot.src); // I was fetching this from my project directory to pull its binary
  const buf = await res.arrayBuffer();
  
  const bin = new TextDecoder('latin1').decode(new Uint8Array(buf));
  setData(bin);
 })();
}, []);

files["/public/images/parrot.jpg"] = { code: data };

<Sandpack>

```js src/App.js

export default function Gallery() {
  return (
    <div>      
      <img src="/public/images/parrot.jpg" width="240" alt="parrot" />

...

The only reliable way I have been able to display the image on my Sandpack instance, is if I base64 the image and ignore the /public/ directory entirely:

  files['/src/images/parrot.js'] = {
    code: `export default 'data:image/jpeg;base64,/9j/2wCEAAUEBAUEAwUFBA...'`,
    hidden: false // just did this to see the output in the Sandbox tab
  };


// then in my Sandpack block
<Sandpack>
```js src/App.js
import parrot from './images/parrot.js' // no '/public/'

export default function Gallery() {
  return (
    <div>
      <img src={parrot} width="240" alt="parrot" />

Unfortunately this seems to ignore the pattern around Serving static files altogether.

brmendez avatar Nov 21 '25 17:11 brmendez