Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How do you pass jwt token to server in the api call in ReactJS

Introduction

Welcome to the world of web programming, where we try to make our applications secure, efficient, and user-friendly. As a beginner, you might have come across terms like 'ReactJS', 'API calls', and 'JWT tokens'. Don't worry if they sound like a foreign language to you. In this blog, we will demystify these terms and learn how to pass JWT tokens to a server in an API call using ReactJS.

Understanding the Basics

Before we dive into the technicalities, let's understand some fundamental concepts.

ReactJS

ReactJS is a JavaScript library used in web development to build interactive elements on websites. It's like the Lego blocks that developers use to build the user interface (UI) of a website. The beauty of ReactJS lies in its component-based architecture, which makes the code reusable and easier to manage.

API Call

API, short for Application Programming Interface, is a set of rules that allows different software applications to communicate with each other. It's like a waiter in a restaurant. You (the user) give your order (request) to the waiter (API), and he brings back your food (response) from the kitchen (server).

An API call is simply a request made by the software to a server via an API. It's like calling the waiter and placing your order.

JWT Tokens

JWT stands for JSON Web Tokens. It's a standard for securely transmitting information between parties as a JSON object. Think of it as a special ticket that grants you access to a concert. The ticket contains information about you (the user) and the concert (the server). The security personnel at the concert (the server) verifies your ticket (JWT token) and grants you access.

Passing JWT Tokens in ReactJS

Now that we have a basic understanding of the concepts, let's see how to pass JWT tokens to a server in an API call using ReactJS.

Imagine you're creating a concert booking website. You want to ensure that only users with valid tickets can access the concert details. Here's how you can do it:

Step 1: Installing the Required Packages

Before we start, we need to install a couple of packages - 'axios' and 'jwt-decode'.

Axios is a promise-based HTTP client for making HTTP requests, and 'jwt-decode' is a library that helps decode JWT tokens.

To install these packages, open your terminal and run the following commands:

npm install axios
npm install jwt-decode

Step 2: Making an API Call

Let's start by making a simple API call without the JWT token.

import axios from 'axios';

axios.get('https://my-concert-website.com/api/concerts')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

The above code sends a GET request to the server to fetch the concert details. The server responds with the data which we log onto the console.

Step 3: Adding JWT Token

Now, let's add a JWT token to our API call. We'll store the token in a variable and add it to the headers of our request.

import axios from 'axios';
import jwt_decode from 'jwt-decode';

const token = 'your-jwt-token'; // The JWT token you received when the user logged in

const decodedToken = jwt_decode(token); // Decoding the token to get user details

console.log(decodedToken);

axios.get('https://my-concert-website.com/api/concerts', {
  headers: {
    Authorization: `Bearer ${token}`
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

The 'Authorization' header is a standard HTTP header used for authorizing requests. It includes the type of authorization (in our case, 'Bearer') followed by the token.

Conclusion

And there you have it! You've successfully learned how to pass JWT tokens to a server in an API call using ReactJS. It's like giving your special concert ticket to the security personnel and gaining access to the concert.

Remember, learning programming is like learning a new language. It might seem overwhelming at first, but with practice and patience, you'll get the hang of it. So keep coding, keep exploring, and most importantly, keep having fun.