5

I have a React app with backend API written in Express (all /api calls are proxied there).

Upon successful user authentication, I will be generating a session ID and storing it somewhere on the client side so that I can later authorise requests to the API.

What is the best practice of implementing this architecture on the Express side? Shall I just send the session ID along with the body of each API request and then precede all backend calls with an authorisation mechanism? Or is there some better/easier way of doing this?

2 Answers 2

5

My intuition would be to take two steps.

  1. On the client, set up your HTTP client to pass the sessionID as a header. You can set custom headers using an HTTP client like axios or, in ES6, fetch, and apply those headers to every request send to your Express API.

  2. Set up a middleware function on your app that will run on every request received by the server. Express has an easy way to do this using app.all("*", yourAuthFunction). You can also take a look at app.use for applying a middleware to more specific routes. This will ensure that your sessionID gets verified on the server before any data is sent in response to the client. Of course, you'll have to write the auth function to work how you'd like.

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

0

When the user successfully authenticated (it should auth' anytime the page loads), a response should be sent to it (contains the session token). Every other request should be authenticated with the session token that received on the authentication response. You can store this token value into hidden input <input name="session" type="hidden" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.