Fetch not working when trying to host site on Github pages but working locally? We’ve got the fix!
Image by Steph - hkhazo.biz.id

Fetch not working when trying to host site on Github pages but working locally? We’ve got the fix!

Posted on

Are you frustrated that your website is working perfectly on your local machine, but when you try to host it on Github pages, your fetch requests just won’t budge? You’re not alone! This is a common issue that many developers face, and today, we’re going to tackle it head-on.

What’s going on?

Before we dive into the solution, let’s take a step back and understand what’s happening. When you make a fetch request on your local machine, it works because your browser is making a request to `http://localhost:xxxx`, which is a trusted origin. However, when you host your site on Github pages, the origin changes to `https://your-username.github.io`, which is a different story altogether.

Github pages, by default, does not support CORS (Cross-Origin Resource Sharing) requests. This means that when your browser tries to make a fetch request to an external API or resource, Github pages blocks it due to security concerns. This is why your fetch requests are failing, even though they work locally.

Solution 1: Proxying requests through your backend

One way to get around this issue is to set up a proxy server on your backend. This way, your frontend can make requests to your backend, which then forwards the request to the external API or resource. This approach requires a bit more work, but it’s a great solution if you’re already using a backend technology like Node.js or Ruby on Rails.

Here’s an example of how you can set up a proxy server using Node.js and Express.js:


const express = require('express');
const app = express();

app.use(express.json());

app.use('/api', (req, res) => {
  const apiUrl = 'https://external-api.com/data';
  fetch(apiUrl)
    .then(response => response.json())
    .then(data => res.json(data))
    .catch(error => console.error(error));
});

app.listen(3000, () => {
  console.log('Proxy server listening on port 3000');
});

In this example, we’re creating an Express.js server that listens on port 3000. When a request is made to `/api`, the server fetches the data from the external API and sends it back to the client as JSON.

On the client-side, you can make requests to your proxy server like this:


fetch('/api')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Solution 2: Using CORS proxies

If you don’t have a backend setup or don’t want to bother with proxying requests, you can use a CORS proxy service. These services act as an intermediate layer between your frontend and the external API, adding the necessary CORS headers to the response.

One popular CORS proxy service is AllOrigins. Here’s how you can use it:


fetch(`https://api.allorigins.win/raw?url=https://external-api.com/data`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we’re making a request to `https://api.allorigins.win/raw`, passing the external API URL as a query parameter. AllOrigins then makes the request to the external API and returns the response with the necessary CORS headers.

Solution 3: Using a Github pages workaround

If you’re using a static site generator like Jekyll or Hugo, you might be able to use a workaround specific to Github pages. Github pages allows you to create a `gh-pages` branch, which can be used to serve static files.

One way to get around the CORS issue is to create a `proxy.html` file in your `gh-pages` branch, which makes the fetch request on behalf of your main page. Here’s an example:


// proxy.html
<script>
  fetch('https://external-api.com/data')
    .then(response => response.json())
    .then(data => {
      const iframe = document.getElementById('proxy-iframe');
      iframe.contentWindow.postMessage(data, '*');
    })
    .catch(error => console.error(error));
</script>

<iframe id="proxy-iframe" srcdoc="" frameborder="0" width="0" height="0"></iframe>

In this example, we’re creating an iframe that loads the `proxy.html` page. The iframe makes the fetch request to the external API and sends the response back to the main page using the `postMessage` API.

On your main page, you can then receive the message like this:


<script>
  window.addEventListener('message', event => {
    if (event.data) {
      console.log(event.data);
    }
  });
</script>

<iframe src="proxy.html" frameborder="0" width="0" height="0"></iframe>

Conclusion

In this article, we’ve covered three solutions to the fetch not working issue when hosting a site on Github pages but working locally. Whether you choose to set up a proxy server, use a CORS proxy service, or employ a Github pages workaround, there’s a solution that’s right for you.

Remember, the key to overcoming this issue is to understand the root cause – Github pages’ lack of CORS support – and find a way to work around it. With a little creativity and some clever coding, you can get your fetch requests working in no time!

Frequently Asked Questions

  1. What is CORS?

    CORS stands for Cross-Origin Resource Sharing. It’s a security feature implemented in web browsers to prevent web pages from making requests to different origins (domains, protocols, or ports) than the one the web page was loaded from.

  2. Why does Github pages block CORS requests?

    Github pages blocks CORS requests as a security measure to prevent malicious scripts from making unauthorized requests to external APIs or resources.

  3. Can I use a different hosting platform to avoid this issue?

    Yes, you can! Some hosting platforms, like Vercel or Netlify, support CORS requests out of the box. However, this might not be an option for everyone, especially if you’re already invested in the Github ecosystem.

Solution Pros Cons
Proxying requests through your backend Maximum control over the request, can handle complex logic Requires backend setup, can be complex to implement
Using CORS proxies Easy to implement, no backend setup required Dependent on third-party services, may have rate limits
Using a Github pages workaround Works specifically for Github pages, no backend setup required Can be complex to implement, might not be suitable for all use cases

By following the solutions outlined in this article, you should be able to get your fetch requests working on Github pages. Happy coding!

Here are 5 Questions and Answers about “Fetch not working when trying to host site on Github pages but working locally”:

Frequently Asked Question

Get stuck with Fetch API issues on Github Pages? Don’t worry, we’ve got you covered!

Why does my Fetch API work locally but not on Github Pages?

This is likely due to CORS (Cross-Origin Resource Sharing) policies. When you run your site locally, it’s not subject to the same-origin policy, which allows Fetch to work as expected. However, when you host your site on Github Pages, it’s subject to the same-origin policy, and Fetch requests are blocked by default. You’ll need to configure CORS headers to allow cross-origin requests.

How do I configure CORS headers on Github Pages?

You can configure CORS headers by adding a `headers` section to your `github.io` repository’s `_config.yml` file. For example, you can add the following code to allow Fetch requests from any origin: `headers: { Access-Control-Allow-Origin: “*” }`. This will enable CORS and allow Fetch requests to work on your Github Pages site.

Do I need to add any specific headers to my Fetch request?

Yes, you should add the `mode: ‘cors’` header to your Fetch request to enable CORS. You can do this by adding the following code to your Fetch request: `fetch(url, { mode: ‘cors’ })`. This will instruct the browser to include CORS headers in the request.

Will configuring CORS headers affect my site’s security?

Configuring CORS headers can potentially introduce security risks if not done correctly. By allowing cross-origin requests, you may expose your site to attacks from malicious actors. To minimize risks, you should only allow CORS requests from trusted domains and limit the types of requests that can be made.

Are there any alternative solutions to configuring CORS headers?

Yes, there are alternative solutions to configuring CORS headers. One approach is to use a proxy server to forward requests from your client-side application to your API. This can help avoid CORS issues altogether. Another approach is to use a library like Axios, which provides built-in support for CORS requests.

Leave a Reply

Your email address will not be published. Required fields are marked *