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
First of all, declare axios config as :
In your component :
don’t forget to init the env var in your env file:
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.