Tuesday, November 17, 2020

storybook composition embedding static storybooks - the CORS silver bullet (get it? like the beer? oh never mind)

TLDR: if you're needing to make an end run around CORS/Access-Control-Allow-Origin errors while hitting a locally running http server, you can try running 

npx http-server . -p 9999 --cors='*'

(Obviously you can pick your own content directory and port besides . and 9999)

Giant pain tracking this down.

It's trivially easy to embed an existing running storybook into your "local" storybook

Just add something like 

  refs: {
   'design-system': {
     title: "Storybook Design System",
     url:"http://localhost:9999/"
   }

to the modue.exports in main.js or ts or whatever.

But what if that other storybook is static? (i.e. the files you generate with npm run build-storybook?)

At first it won't work, and you may see requests for /stories.json

The docs aren't crystal clear on it, but you need to run 

npx sb extract

in order to generate that file. 

But once that was done I was still seeing:
Access to fetch at 'http://localhost:9999/stories.json' from origin 'http://localhost:6008' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Luckily bardiarastin on this github page had an answer:

npx http-server . -p 9999 --cors='*'

That seemed to clear it up and Storybook composition worked.

No comments:

Post a Comment