DEV Community

Cover image for Introducing the New and Improved Cookies package for Meteor.js
Dmitriy A.
Dmitriy A.

Posted on

Introducing the New and Improved Cookies package for Meteor.js

Meteor.js has long been celebrated for its seamless isomorphic development experience, where the same code can run on both the client and the server. Among the many challenges in building robust, real-world web applications is cookie management. The ostrio:cookies package has evolved over the years to become a bulletproof solution for handling cookies in Meteor applications. In this article, I'll explore the package's history, highlight its recent improvements, discuss common usage patterns, and demonstrate why it's an indispensable tool in a Meteor developer's toolbox.

Today this package is 10 years old and I'm happy to announce it 34th package release ā€” šŸŖ ostrio:cookies@2.9.0

TL;TR;

The new release of ostrio:cookies marks a significant milestone in cookie management for Meteor.js applications. With full compatibility with Meteor 3, TypeScript support, enhanced documentation, and robust testing, this package is designed to simplify one of the most common yet challenging tasks in web development. Continue reading to learn more.

About ostrio:cookies package

Originally created to simplify cookie management in Meteor.js, ostrio:cookies quickly became popular among Meteor developers for its isomorphic API that worked seamlessly on the client and the server. Over time, as Meteor evolved and new web standards emerged, the package has undergone significant refactoring and modernization.

Package facts and achievements:

Key milestones include:

  • Early Adoption: The initial release provided basic cookie functions (get, set, remove) that worked for both client and server environments, enabling developers to manage cookies without worrying about environment-specific quirks.
  • Isomorphic Enhancements: With the advent of Meteor 1.3 and beyond, the package was updated to handle both Node.js and browser-specific APIs, ensuring compatibility across Cordova, Meteor-Desktop, and other Meteor-supported environments.
  • Modernization and Refactoring: In today's release I introduced a new CookiesCore class for low-level cookie management, enhanced error handling, and better middleware integration. The codebase now features 100% JSDoc coverage, robust tests covering nearly all usage cases, and optimized performance.

What's New in the Latest Release

The latest release of ostrio:cookies brings a host of improvements and new features:

  • šŸ¤ Meteor 3 Compatibility: Full support for the latest version of Meteor ensures you can leverage the newest platform enhancements.
  • šŸ¤“ TypeScript Definitions: Comprehensive TypeScript support now allows for better type checking and IDE auto-completion, making development smoother and less error-prone.
  • šŸ“” Enhanced Documentation: With 100% JSDoc coverage and improved documentation, you now have access to detailed examples and usage guides right at your fingertips.
  • āœØ Added .sendAsync() client method for asynchronous cookie synchronization, matching Meteor 3 APIs.
  • āœØ Introduced .destroy() server method to cleanly unregister middleware and free resources.
  • āœØ Extended .set(key, value, opts) now supports modern cookie attributes like partitioned and priority.
  • šŸš€ Performance Optimizations: Deprecated methods have been replaced, and the codebase has been fine-tuned for optimal performance in both client and server environments.
  • šŸ‘Øā€šŸ”¬ Robust Test Suite: New test suite now covers 99.9% of the codebase, ensuring stability and reliability across a wide range of usage scenarios.

Read full and detailed v2.9.0 release-notes

Meteor.js is Great for Web App Development

Meteor.js offers a unique development experience by combining client and server code in a single codebase. Some key benefits include:

  • Isomorphic Code: Write once, run everywhere. With Meteor, your code can seamlessly execute on both the client and server, reducing the overhead of maintaining separate codebases.
  • Real-Time Data and Reactivity: Meteor's built-in data synchronization and reactive programming model allow developers to build dynamic, real-time web applications with ease.
  • Rapid Prototyping: Meteor's integrated build system and package ecosystem enable rapid development and deployment, making it ideal for startups and agile development teams.
  • Robust Community and Ecosystem: The rich ecosystem of Meteor packages, such as ostrio:cookies, provides solutions to common challenges, enabling you to focus on building unique application features rather than reinventing the wheel.

Use Cookies in Meteor apps as you do in any other framework

Cookie management is a critical aspect of web development. Whether you're handling user authentication, session management, or simply storing preferences, a reliable cookie library is essential. Here's how ostrio:cookies can help:

  • Isomorphic API: Use the same API to set, get, and remove cookies on both the client and the server. This consistency reduces bugs and simplifies debugging.
  • Advanced Features: With support for modern cookie features, your application can meet the latest web standards and security requirements.
  • Middleware Integration: On the server side, ostrio:cookies provides middleware that automatically attaches a Cookies instance to incoming requests. This makes it easy to integrate with other server-side logic and third-party packages.
  • Type Safety and Documentation: With TypeScript definitions and detailed JSDoc comments, you get an IDE-friendly experience that minimizes runtime errors and speeds up development.
  • Comprehensive Testing: The robust test suite ensures that the package handles a wide range of use cases, including edge cases and asynchronous operations, so you can deploy your application with confidence.

Examples

For more examples see "Examples" section in the updated ostrio:cookies package docs

Basic Client Usage

Use cookies on the Client (Browser, Cordova, Desktop, etc.):

import { Cookies } from 'meteor/ostrio:cookies';

const cookies = new Cookies();
cookies.set('userToken', 'abcdef123456', { path: '/', secure: true });
const token = cookies.get('userToken');
cookies.remove('userToken');
Enter fullscreen mode Exit fullscreen mode

Basic Server Usage

Build server logic in the handler callback

import { WebApp } from 'meteor/webapp';
import { Cookies } from 'meteor/ostrio:cookies';

const cookiesInstance = new Cookies({
  handler(cookies) {
    // Custom processing: for example, remove a test cookie
    if (cookies.has('test-cookie')) {
      cookies.remove('test-cookie');
    }

    // Add or remove cookies based on URL or path
    const url = new URL(cookies.response.req.url);
    if (url.pathname === '/signup/create') {
      // Set cookie based on get-query
      const plan = url.searchParams.get('plan') || 'default-plan';
      cookies.set('selected-tariff', plan);
    }

    if (url.pathname === '/shopping-cart/new') {
      // Create new cookie with checkout session
      const plan = url.searchParams.get('plan') || 'default-plan';
      cookies.set('checkout-session', Random.id());
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

Cookie Synchronization

Call .send() or .sendAsync() on the client to sync cookies with server

import { Cookies } from 'meteor/ostrio:cookies';

const cookies = new Cookies();
cookies.set('asyncTest', 'value123');

const response = await cookies.sendAsync();
if (response.ok) {
  console.log('Cookies synced successfully. On server "synced" cookies trigger `onCookie` hook');
}
Enter fullscreen mode Exit fullscreen mode

šŸ“” Read ostrio:cookie updated and detailed documentation

Try managing Cookies in Meteor apps today!

Give ostrio:cookies a try (if you haven't yet) in a Meteor project and experience the ease and reliability of modern cookie management!

Join the community

Top comments (2)

Collapse
 
smart_egg profile image
Dmitriy A.

Do you have a question or want to discuss implementation related to cookies? Iā€™d be happy to brainstorm it here in comments

Collapse
 
distalx profile image
D

It's impressive to see how far the ostrio:cookies package has come over the last decade. I appreciate the detailed examples you provided. Keep up the fantastic work!