How to set a HttpOnly cookie via JavaScript?
HttpOnly cookie can only be set on the server-side. The scripting languages like JavaScript have no API available to get/set the HttpOnly attribute of the cookie.
If we want JavaScript to set the HttpOnly cookie, we can send an AJAX call to the backend and have the backend set the HttpOnly cookie.
If we are using Node.js (JavaScript in the backend) we can write the following code to set the HttpOnly cookie.
The following is the code segment:
response.setHeader('Set-Cookie', 'cookieName=cookieValue; HttpOnly');
If you want to set multiple cookies, with HttpOnly. The code would be:
response.setHeader('Set-Cookie', ['username=joe; HttpOnly', 'age=25; HttpOnly']);
If you want to set multiple cookies, some of them HttpOnly and some of them without HttpOnly. The code would be:
response.setHeader('Set-Cookie', ['username=joe; HttpOnly', 'age=25; HttpOnly', 'status=active']);