Skip to content

Working with Cookies

Marissa Shey edited this page Apr 1, 2020 · 5 revisions

What Are Cookies?

Whenever you visit a website and make requests, those requests are stateless meaning the server has no way to connect a previous requests to the current request. This can make keeping track of certain user actions difficult. Cookies are small piece of data that the server can send to your browser that are then stored on your computer. Whenever you make any requests to a server, the browser automatically sends all the cookies with the requests. Thus a server can read the cookies to get data about you. In short, cookies are another way to pass information from the front end to the back end but the information lasts over multiple requests.

How does Connected use Cookies?

When a user logs in, we receive a utorid from the Uoft Web Login page. However, this is only sent once. So how do we keep track of if a user has already logged in or not? Cookies!

Every time a user logs in, we check for the utorid header and if it exists, we create a cookie with the utorid which we then pass to the users computer. Then, if the cookie is present on the computer, we know the user is logged in. If the cookie is not present, we know the user is not logged in.

How can you create a Cookie?

In express, we have the cookie-parser package installed that allows us to create and modify cookies. To create a cookie simply use res.cookie('cookie-name', 'cookie-value') within a request on the server.

  • res is the response object
  • cookie-name is the name of the cookie ie utorid
  • cookie-value is what the cookie is set to ie the utorid of the user

How can a read a cookie on the front end

The AuthenticationService contains helper methods that you can use to retrieve the cookie data and check if a user is logged in. First, create a method that calls the service like so:

        methods:{
            isLoggedIn(){
                return AuthenticationService.userIsLoggedIn(this.utorid);
            }
        }

Then you can all the created method within your html template.

<b-button v-if="isLoggedIn()" class="btn-sm">

If you want to retrieve the utorid cookie directly within the JavaScript of a Vue file, you can use this.$cookies.get('utorid').

If you need to update or change the value of a cookie in the front end you can use this.$cookies.set('cookie_name', 'new_value).

You can remove a cookie using this.$cookies.remove('cookie_name').

You can read the vue-cookies documentation for more information about working with cookies in vue.

Clone this wiki locally