Adding Cross-Origin Resource Sharing
Cross-Origin Resource Sharing, or CORS, allows you to serve static resources from a project you have on Surge, to sites and applications you have on other domains. This is useful for:
- Sharing web fonts files on the Surge CDN across domains, for use in CSS with
@font-face
- Sharing SVG icons, WebGL textures, and other static resource on the Surge CDN across domains
- Requesting resource across sites using
XMLHttpRequest
from the Surge CDN
Now, you can access these resources client-side on your other project without incurring Cross-Origin errors. This is done by adding a CORS
file (no extension) in the root of the directory you want to publish.
Follow along
An open source companion to this guide is available on GitHub.Adding a CORS
file
First, create a CORS
file using your favourite text editor, or the command line:
sh
touch CORS
Allow your fonts, SVG files, and other resources to be accessed client-side from any other domain, by adding *
into the CORS
file:
*
You can also create this file and add *
into it, all with one command:
echo '*' > CORS
Adding CORS for specific domains only
If you want your resources to be setup for CORS, but only with a specific, other domain, you may list it in the CORS
file instead. For example:
https://blog.example.com
You may also list multiple domains in the file:
https://blog.example.com
https://example.com
https://surge.sh
Publishing your project
Your project should now have a CORS
file inside the root of the directory you are going to deploy. Publish it by running surge
:
surge
Here are the results of requesting the .woff2
file on in this project using test-cors.org.
Now, your project is live on the web with CORS support.
Upgrade to Surge Professional
CORS
files are available with Surge Professional. When you publish, you’ll be prompted to upgrade your account right from the CLI.