skip to Main Content

Currently im working on a CRUD application using React,Node,Express and Mysql and im new to it
the issue i’m facing is i’m having a session JWT token which is getting from backend and storing in the session.
but i’m not getting on how to pass it through all the request as a header to the backend to verify it
i’m having around 30-40 api link also which i’m calling directly as of now
eg: const response = await axios.post(http://localhost:4000/confirm/${Id}, {
…data,
});

i know it’s a bad practice to call api like this directly but i’m not getting on where to store them and call properly with passing the session id along with this to backend

i tried to put the api to .env file but didn’t get how to pass the dynamic url variable through that

2

Answers


  1. First of all, declare axios config as :

    axios.js
    
    import axios from 'axios';
    
    const instance = axios.create({
      baseURL: process.env.REACT_APP_API_BASE_URL, // Set your base URL in your .env file
    });
    
    instance.interceptors.request.use(
      (config) => {
        const token = sessionStorage.getItem('jwtToken'); // Get your JWT token from session storage or wherever you store it
    
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
    
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    
    export default instance;
    

    In your component :

    import axios from './axios'; // Import the Axios instance
    
    async function fetchData(Id, data) {
      try {
        const response = await axios.post(`/confirm/${Id}`, data);
        // Handle the response
      } catch (error) {
        // Handle errors
      }
    }
    

    don’t forget to init the env var in your env file:

    REACT_APP_API_BASE_URL=http://localhost:4000
    
    Login or Signup to reply.
  2. I’m no expert here (it’s my first answer in StackOverflow) but maybe I can point you to something from my experience using NextAuth and having a lot of problems myself to handle authentication properly.

    I guess you’re trying to make protected routes. I don’t really know how to do that properly, but let me ask you something because if it fits your needs, it’s way easier!

    What I did was that I had in the frontend different interaction possibilities on whether user is authenticated or not. The only verification I did was on login, then store the token in the browser and serve different frontends for authenticated / not authenticated. In fact, not authenticated users (aka not a token in the browser) in my app only had access to login/signup page.
    Once you are authenticated, you do the check in the client before the fetch.
    Would that fit your needs?

    I guess you still could handwrite the urls with queries, but to be hacked that way the person should have your other users session id. I don’t think I’m offering here a full solution, as I said, I ended up using NextAuth.

    I hope I was helpful at the least!

    UPDATE: Seen the answer that is posted, I think it’s doing kind of the same, probably better. But it’s not responding to your question about server-side verification. But maybe I’m not fully understanding the code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search