šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Your first serverless API call with Cloudflare and vanilla Javascript

To get started with your first serverless function call using Cloudflare Workers and vanilla JavaScript we will first need to create a Cloudflare account.

So, if you don't already have an account yet, sign up for one. Cloudflare offers a free tier that's perfect for experimentation and small project apps.

Now that your account is up and running go to the Workers & Pages section and add a new worker.

Your worker will be reachable at a URL like the one below:

https://WORKER_NAME_HERE.YOUR_USERNAME_HERE.workers.dev

Cloudflare also provides a code editor where you can play with the worker.

For our first example, we will just return a simple JSON message:

export default {
  async fetch(request) {
    const data = {
      message: "Hello Js Craft!",
    };

    const json = JSON.stringify(data, null, 2);

    const headers = {
      'content-type': 'application/json;charset=UTF-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    };

    return new Response(json, {
      headers,
    });
  },
};

Note that you will need to enable the Access-Control-Allow-Origin header to be able to make the call.

Having the worker in place we can now write a simple vanilla Javascript fetch that will call the Javascript serverless function and print the result:

<body>
    <button id="btn">Call serverless Cloudflare function</button>
    <script>
        document.getElementById('btn').addEventListener('click', () => {
          fetch('https://js-craft-first.js-craft-feed.workers.dev')
            .then(response => response.json())
            .then(data => alert(data.message))
            .catch(error => alert('ā›”ļø Error fetching data:', error));
        })
    </script>
</body>

And that's it! You have made your first call to a Javascript serverless function.

You can see the running example on Github pages and the full code here.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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