/plushcap/analysis/hasura/best-practices-of-using-jwt-with-graphql

The Ultimate Guide to handling JWTs on frontend clients (GraphQL)

What's this blog post about?

In this guide, we will be building a simple application using Cloudflare Workers and the Hasura GraphQL engine. The app will allow users to create, update, delete posts, and also retrieve all posts. Here's an overview of what we'll be doing: - Setting up our Hasura project with sample data. - Writing a simple Cloudflare worker that will interact with the Hasura GraphQL API. - Deploying our Cloudflare worker to production. Before we begin, make sure you have Node.js and npm installed on your machine. You can download them from https://nodejs.org/en/. Setting up Hasura project First, let's set up a new Hasura project with some sample data. If you don't already have an account, sign up for free at https://hasura.io/signup/. Once logged in, click on the "Create New Project" button: Fill out the form and create your new project. Once created, navigate to the "Data" tab and add a new table called "posts". Add the following columns: - id (int4) - primary key - title (text) - content (text) - author_id (uuid) - foreign key referencing users.id Next, we need to insert some sample data into our posts table. To do this, navigate to the "Data" tab and click on the "Insert Data" button: Fill out the form with some sample post data: Now that we have some sample data in our Hasura project, let's move on to writing our Cloudflare worker code. Writing a simple Cloudflare worker In order to interact with the Hasura GraphQL API from within our Cloudflare worker, we will be using the `@cloudflare/wrangler` CLI tool. If you haven't already installed it, you can do so by running: ```bash npm install -g @cloudflare/wrangler ``` Next, create a new directory for our project and navigate into it: ```bash mkdir hasura-cloudflare-worker && cd $_ ``` Initialize your new project by running: ```bash npx @cloudflare/wrangler init --lang typescript ``` This will create a basic TypeScript Cloudflare worker project structure. Now, let's update our `src/index.ts` file to include the logic for interacting with the Hasura GraphQL API: ```typescript import { Context } from '@cloudflare/workers-types'; // Replace this URL with your own Cloudflare worker URL const HASURA_CLOUDFLARE_WORKER_URL = 'https://example.com/.netlify/functions/hasura-graphql-engine'; export default { async fetch(request: Request, env: Env, ctx: Context): Promise<Response> { // Parse the request body as JSON const data = await request.json(); // Determine which operation to perform based on the request method switch (request.method) { case 'POST': { // Perform a mutation operation return this.performMutationOperation(data, env); } case 'GET': { // Perform a query operation return this.performQueryOperation(env); } default: { // Handle other request methods (e.g., DELETE) return new Response('Method not supported', { status: 405 }); } } }, async performMutationOperation(data: any, env: Env): Promise<Response> { // Convert the JSON data into a URL-encoded string const formData = new FormData(); for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { formData.append(key, data[key]); } } // Make a POST request to the Hasura GraphQL API with our mutation operation payload const response = await fetch(`${HASURA_CLOUDFLARE_WORKER_URL}?action=post&data=${formData.toString()}`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); // If the response status code is not 20, return an error response if (!response.ok) { return new Response(JSON.stringify({ message: 'An error occurred while performing the mutation operation' }), { status: 500 }); } // Otherwise, return a success response with the updated data from Hasura const updatedData = await response.json(); return new Response(JSON.stringify(updatedData), { headers: { 'Content-Type': 'application/json' }, status: 20 }); }, async performQueryOperation(env: Env): Promise<Response> { // Make a GET request to the Hasura GraphQL API with our query operation payload const response = await fetch(`${HASURA_CLOUDFLARE_WORKER_URL}?action=get`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); // If the response status code is not 20, return an error response if (!response.ok) { return new Response(JSON.stringify({ message: 'An error occurred while performing the query operation' }), { status: 500 }); } // Otherwise, return a success response with the retrieved data from Hasura const retrievedData = await response.json(); return new Response(JSON.stringify(retrievedData), { headers: { 'Content-Type': 'application/json' }, status: 20 }); }, }; ``` In this code, we define two main functions for performing mutation and query operations against the Hasura GraphQL API. The `performMutationOperation()` function takes in JSON data representing our mutation operation payload (e.g., createPost, updatePost, deletePost), while the `performQueryOperation()` function does not take any arguments since it only retrieves all posts from the database. Deploying our Cloudflare worker to production Now that we have written our Cloudflare worker code, let's deploy it to production using the `@cloudflare/wrangler` CLI tool. First, make sure you are logged in to your Cloudflare account by running: ```bash npx @cloudflare/wrangler whoami ``` If you see a message saying "Logged in as [your email address]", then you should be good to go! Next, build and deploy our Cloudflare worker code by running: ```bash npx @cloudflare/wrangler publish --name hasura-graphql-engine ``` This will compile our TypeScript code into JavaScript, upload it to a new Cloudflare worker on your account, and then enable traffic routing for that worker. Once deployed, you should see a message like this: ``` ✅ Everything looks good! Name: hasura-graphql-engine Domain: [your project domain] ID: [your worker id] Status: live Deployed at: 2021-02-11T18:47:56.397Z ``` And that's it! You now have a simple application built using Cloudflare Workers and the Hasura GraphQL engine. To test out your new app, simply navigate to the URL of your deployed Cloudflare worker (e.g., https://[your project domain]/.netlify/functions/hasura-graphql-engine) in your web browser or use a tool like Postman or CURL to send HTTP requests directly to your Cloudflare worker's URL. Note: Since we are using the free tier of Hasura Cloud for this example, please note that there may be some limitations on usage and performance depending on how much traffic you generate with your app. If you find that these limits are causing issues for your users, consider upgrading to one of the paid tiers offered by Hasura Cloud. References: - https://hasura.io/learn/graphql/ - https://developers.cloudflare.com/workers/get-started/ - https://www.npmjs.com/package/@cloudflare/wrangler

Company
Hasura

Date published
Jan. 4, 2022

Author(s)
Vladimir, Tanmai Gopal, Gavin Ray

Word count
5173

Language
English

Hacker News points
6


By Matt Makai. 2021-2024.