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?
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?
Share Improve this question asked Dec 23, 2017 at 23:47 Marcin WasilewskiMarcin Wasilewski 7351 gold badge10 silver badges26 bronze badges2 Answers
Reset to default 5My intuition would be to take two steps.
On the client, set up your HTTP client to pass the sessionID as a
header
. You can set customheader
s using an HTTP client likeaxios
or, in ES6,fetch
, and apply thoseheader
s to every request send to your Express API.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 atapp.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!
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" />