10

In my usual experience all single page apps I worked on used JWT as authentication mechanism. I came across api that uses httpOnly cookies for this.

Since we can't access such cookie via javascript to know if it is present or not, how does one handle this in react app?

My initial idea was to track this by setting some sessionStorage upon successful sign in and removing it if I receive an error related to authentication.

But this doesn't work well with next.js server side rendering I believe? We have it set up with apollo client which allows setting custom headers and cache.

Is there a common way to handle this authentication process with set up above?

Ilja
  • 44,142
  • 92
  • 275
  • 498

1 Answers1

5

httpOnly just means that the value can't be read by JavaScript.

So you make an HTTP request to the server and it will return a response with a Set-Cookie header.

Then any future requests will automatically include the cookie.

(Just make sure that you set withCredentials or the equivalent.)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @EricBurel — That's a matter of opinion, and dependant on context. – Quentin Mar 02 '21 at 17:56
  • I am trying to gather info on this precise subject, which is not often covered in articles about auth, do you have examples of contexts where one can be preferred upon the other? In Next one specific problem with `localStorage` is that you can't get the auth token during SSR, since you have no control over the request content. – Eric Burel Mar 02 '21 at 17:59
  • There isn't space in the comments of an SO question for a decent discussion on the topic. – Quentin Mar 02 '21 at 18:01