How to get a cookie in JavaScript

Retrieving cookie values in JavaScript requires parsing the document.cookie string to extract specific cookie data for application use. As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve implemented cookie retrieval in countless production applications for user session management. The most reliable approach creates a helper function that splits the cookie string and finds the specific cookie by name. This method provides consistent cookie access while handling edge cases like missing cookies and special characters.

Create a helper function that parses document.cookie to retrieve specific cookie values by name.

function getCookie(name) {
    const value = `; ${document.cookie}`
    const parts = value.split(`; ${name}=`)
    if (parts.length === 2) {
        return parts.pop().split(';').shift()
    }
    return null
}

// Usage
const username = getCookie('username')
console.log(username) // 'JohnDoe' or null if not found

This code creates a getCookie function that adds a semicolon prefix to document.cookie, splits by the cookie name pattern, and extracts the value if found. The function handles the cookie string format properly by finding the exact name match and returning the value up to the next semicolon. It returns null if the cookie doesn’t exist, providing a clean API for cookie retrieval.

Best Practice Note:

This is the cookie retrieval pattern we use throughout CoreUI applications for consistent data access. Always handle null returns gracefully and consider URL decoding cookie values if they contain encoded characters.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author