ArticleZip > How To Set Expiration Date For Cookie In Angularjs

How To Set Expiration Date For Cookie In Angularjs

Setting an expiration date for a cookie in AngularJS is a handy technique that allows you to control how long a cookie remains valid in a user's browser. This approach can help enhance security, manage user preferences, or personalize the user experience. In this guide, we'll walk you through the simple steps to set an expiration date for a cookie in your AngularJS application.

AngularJS provides a convenient way to work with cookies through the ngCookies module. To begin, you need to inject the 'ngCookies' module into your AngularJS application. This module offers a $cookies service, which enables you to create, read, and manipulate cookies within your application.

Let's start by setting an expiration date for a cookie using AngularJS. When creating a new cookie, you can specify the expiration date by adding an additional parameter to the $cookies.put() method. The expiration date is defined in milliseconds from the current time.

Here's an example of how you can set a cookie with an expiration date of one hour from the current time:

Javascript

app.controller('MainController', function($scope, $cookies) {
    var now = new Date();
    var exp = new Date(now);
    exp.setHours(now.getHours() + 1); // Set expiration time to 1 hour from now

    $cookies.put('myCookie', 'cookieValue', { expires: exp });
});

In this example, we create a new Date object to represent the current time. Then, we calculate the expiration time by adding one hour to the current time. By passing this calculated expiration time to the $cookies.put() method as an option, we set the expiration date for the cookie named 'myCookie'.

By setting an expiration date for your cookie, you can control how long the cookie persists in the user's browser. This approach can be useful for implementing features like automatic logouts after a certain period of inactivity or managing session-related information securely.

Remember, the expiration date for a cookie is set in milliseconds, so make sure to calculate the correct time interval based on your requirements. You can adjust the expiration time by changing the value added to the current time in the example code.

In summary, setting an expiration date for a cookie in AngularJS is a straightforward process that offers you the flexibility to manage cookie lifetimes effectively. By utilizing the ngCookies module and the $cookies service, you can control the duration of your cookies to enhance security and improve user experience in your AngularJS application.

Give it a try in your next project and see how setting expiration dates for cookies can benefit your application!

×