logoalt Hacker News

ctmlrtoday at 7:30 AM1 replyview on HN

Backblaze offers 10 GB of free storage and CloudFlare offers free data transfer from B2, with these two you can host a static site for free. I have a worker script that routes requests to the index page and sets cache headers for my site.

  export default {
    async fetch(req, env, ctx) {
      // Cached response
      let res = await caches.default.match(req);
      if (res) return res;
  
      // Fetch object from origin
      let reqPath = new URL(req.url).pathname;
      reqPath = reqPath.replace(/\/$/, ''); // Remove trailing slash
      if (!reqPath.includes('.')) // Check file extension
        reqPath += '/index.html'; // Default to index page
  
      res = await fetch(env.ORIGIN + reqPath);
      if (res.status === 404) // Object not found
        res = await fetch(env.ORIGIN + '/404.html');
  
      // Configure content cache
      res = new Response(res.body, res);
      const ttl = res.headers.get('content-type').startsWith('text')
        ? 14400 : 31536000; // Cache text 4 hours, 1 year default
      res.headers.set('cache-control', 'public, max-age=' + ttl);
  
      // Cache and return response
      ctx.waitUntil(caches.default.put(req, res.clone()));
      return res;
    },
  };

Replies

Gigachadtoday at 7:56 AM

You can do it a lot easier with GitHub pages, but no business owner is going to be able to do either of these.