All files / stores useCookieStore.ts

100% Statements 10/10
75% Branches 3/4
100% Functions 3/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75  2x 2x     2x 2x                                                     2x                                         1x 1x                             1x 1x      
'use client';
import { setCookie, parseCookies } from 'nookies';
import { create } from 'zustand';
import { type CookieState } from '../types/index';
 
const COOKIE_PATH = '/';
const COOKIE_NAME = 'authentication';
/**
 * @module CookieStore
 * @author Munir Mardinli
 *
 * Zustand store for managing authentication token cookies in a Next.js application.
 * Handles both client-side and server-side token persistence with secure cookie settings.
 *
 * @property {string|null} authToken - Current authentication token (null if not authenticated)
 * @property {Function} setAuthToken - Stores a new authentication token
 * @property {Function} removeAuthToken - Clears the current authentication token
 *
 * @example
 * // Access the store in a React component
 * import { useSCookieStore } from './useCookieStore';
 * const token = useSCookieStore(state => state.authToken);
 *
 * @example
 * // Set a new token
 * const setAuthToken = useSCookieStore(state => state.setAuthToken);
 * setAuthToken('my-token');
 *
 * @example
 * // Remove the token
 * const removeAuthToken = useSCookieStore(state => state.removeAuthToken);
 * removeAuthToken();
 */
export const useSCookieStore = create<CookieState>((set) => ({
	/**
	 * Current authentication token
	 * @type {string|null}
	 * @description Automatically initializes from cookies if available
	 */
	authToken:
		typeof window !== 'undefined'
			? parseCookies()?.["authentication"] || null
			: null,
	/**
	 * Stores a new authentication token in both state and cookies
	 * @param {string} token - The JWT or session token to store
	 * @returns {void}
	 *
	 * @description Configures secure cookies in production with:
	 * - Path: {COOKIE_PATH}
	 * - Secure flag (HTTPS only in production)
	 * - SameSite=Lax policy
	 */
	setAuthToken: (token: string) => {
		set({ authToken: token });
		setCookie(null, COOKIE_NAME, token, {
			path: COOKIE_PATH,
			secure: process.env.NODE_ENV === 'production',
			sameSite: 'Lax',
		});
	},
	/**
	 * Clears the authentication token from state and expires the cookie
	 * @returns {void}
	 *
	 * @description Effectively logs out the user by:
	 * - Setting authToken to null
	 * - Expiring the cookie (maxAge: -1)
	 */
	removeAuthToken: (): void => {
		set({ authToken: null });
		setCookie(null, COOKIE_NAME, '', { path: COOKIE_PATH, maxAge: -1 });
	},
}));