Skip to content

Instantly share code, notes, and snippets.

@creuserr
Last active January 24, 2024 07:58
Show Gist options
  • Save creuserr/2e8b6d49d8c10152c606045f563925a4 to your computer and use it in GitHub Desktop.
Save creuserr/2e8b6d49d8c10152c606045f563925a4 to your computer and use it in GitHub Desktop.
🗃️ Effortless GitHub CDN Setup with Vercel and NodeJS

Effortless GitHub CDN Setup with Vercel and NodeJS

Certain CDNs rely on extended caching, expiring after up to 7 days. Consider crafting your own CDN for GitHub repositories. This gist provides a simplified setup and boilerplate for creating your personal GitHub CDN exclusively using Vercel and NodeJS.

Setup

  1. Begin by creating a new repository.
  2. Add the essential files: vercel.json and index.js.
  3. Deploy your repository effortlessly to Vercel.

Usage

Construct URLs using the format:

https://<CDN>.vercel.app/<USER>/<REPO>/<PATH>

Example:

https://crestatic.vercel.app/creuserr/vatch-lite/vatch-lite.js

No CLI usage, no extra installations—just a hassle-free CDN at your fingertips.

module.exports = async function(request, response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Content-Type", "text/plain");
var user = null;
var repo = null;
var path = "";
request.url.split("/").forEach(function(i) {
if(i.trim().length == 0) return;
if(user == null) user = i;
else if(repo == null) repo = i;
else path += `/${i}`;
});
if(path.startsWith("/")) path = path.slice(1);
if(user == null || repo == null || path.length == 0) return response.status(400).send("Error: Incomplete parameter");
var url = `https://api.github.com/repos/${user}/${repo}/contents/${path}`;
try {
var req = await fetch(url);
var json = await req.json();
if(json.content == null) {
return response.status(400).send("Error: Not found");
}
var content = json.content.toString();
return response.status(200).send(unescape(atob(content.replace(/\n/g, ""))));
} catch(e) {
return response.status(400).send(`Error: ${e}`);
}
}
{
"version": 2,
"builds": [{
"src": "index.js",
"use": "@vercel/node"
}],
"headers": [{
"source": "/index.js",
"headers": [{
"key": "Access-Control-Allow-Credentials",
"value": "true"
}, {
"key": "Access-Control-Allow-Origin",
"value": "*"
}, {
"key": "Access-Control-Allow-Methods",
"value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
}, {
"key": "Access-Control-Allow-Headers",
"value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
}]
}],
"rewrites": [{
"source": "/(.*)",
"destination": "/index.js"
}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment