Working With Cookies in Angular
Next step is to create a server-equivalent of service responsible for user interactions. This lesson will show you how to read HTTP requests in Angular, get cookies from it and decrypt them.
Working With Cookies in Angular#
Your application won't be only visited by anonymous users. Some users could navigate directly to the /favorites path to see the list of their favorite products. In this case, even if the user is authenticated, server-side Angular won't recognize them as such and redirect them to the login page. Moreover, the content of the / path depends on the favorites list of the authenticated user.
Navigate to the application in the browser, authenticate (login:
[email protected], password:
abc123), and add a couple of products to the list of favorites.
Now click My Favorite Products and reload the page. Server-side Angular will render the login page although you clearly have the authentication cookie!
Now switch to Postman and obtain the authentication cookie by sending a POST request to /api/login with the following body:
Once you receive a response, Postman saves the cookie, and it's used with further requests as long as its
expires value is valid.
Perform a GET request to /. As you can see, all products can be added to favorites.
You can perform that test using cURL as well:
To address the problem described above, you need to create
UserServerService similar to the existing
Providing a function reference to Angular#
First things first, let's generate a new service with the following CLI command:
In this service, you're going to read cookie content and retrieve user data from the database. The cookie is encrypted with a key stored on the server. It would be best if you had a function that decrypts the cookie to read its content. You will obtain it in the same way you obtained the
dbConnection object - by injecting it from server.ts to Angular.
decrypt() function from api.ts:
Import it into server.ts and provide to Angular in the
You can now inject this function in the constructor of
UserServerService along with other services:
Getting cookie content in Angular#
You now have the
MongoService, and the
request object. Everything is ready to obtain a user ID from the request cookie and retrieve their data from the database. Start by adding the import statements that you are going to use in this part:
request object you have in Angular is not equivalent to what you have in Express.js (server.ts). There is no
.cookies field to easily retrieve a cookie's names and values. You have request headers though, so with a little bit of play, you can build up that object yourself.