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.

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 ProductsServerService.

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.

Export the decrypt() function from api.ts:


This page is a preview of The newline Guide to Angular Universal

Start a new discussion. All notification go to the author.