Cookie

  • 1. Files

    Installation

    
                      npm install --save cookies-next
    

    2. Usage

    Create a cookie:
    
    import { setCookie } from 'cookies-next';
    
    setCookie('key', 'value', options);
    
    Read a cookie:
    
    import { getCookie } from 'cookies-next';
    
    getCookie('key', options); // => 'value'
    getCookie('nothing', options); // => undefined
    
    Read all cookies:
    
    import { getCookies } from 'cookies-next';
    
    getCookies(options); // => { 'name1': 'value1', name2: 'value2' }
    
    Check if a cookie exists:
    
    import { hasCookie } from 'cookies-next';
    
    hasCookie('name', options); // => true
    hasCookie('nothing', options); // => false
    
    Delete a cookie:
    
    import { deleteCookie } from 'cookies-next';
    
    deleteCookie(name, options);
    

    Usage of Cookie in middleware

    
    import { NextResponse, NextRequest } from 'next/server'
    
    export function middleware(request: NextRequest) {
    	// Get a cookie
    	request.cookies.get('myCookieName')?.value
    
    	// Get all cookies
    	request.cookies.getAll()
    
    	// To change a cookie, first create a response
    	const response = NextResponse.next()
    
    	// Set a cookie
    	response.cookies.set('myCookieName', 'some-value')
    
    	// Setting a cookie with additional options
    	response.cookies.set({
    		name: 'myCookieName',
    		value: 'some-value',
    		httpOnly: true,
    	})
    
    	// Delete a cookie
    	response.cookies.delete('myCookieName')
    
    	return response
    }