Browser APIs; Web storage, DOM, Fetch, and Geolocation.

Browser APIs; Web storage, DOM, Fetch, and Geolocation.

While writing Next.js, I encountered a bug that was a result of a browser API (Local Storage) being rendered on the server and thus I decided to deep dive into some of the browser APIs to get versed knowledge just out of curiosity. Here is curated documentation of the knowledge hunt.

Browser APIs:

  • Programming interfaces provided by web browsers

  • Enable web applications to interact with browser and device features

  • Key types include:

    • DOM API (manipulate web page)

    • Geolocation API (access device location)

    • Fetch API (make network requests)

    • Web Storage API (store data in browser)

  1. DOM (Document Object Model) API: Purpose:

  • Allows JavaScript to interact with HTML/XML documents

  • Represents webpage as a tree of objects (nodes)

  • Enables dynamic content manipulation

Key Capabilities:

  • Select elements

  • Modify content

  • Create/remove elements

  • Change styles

  • Handle events

Example:

// Selecting elements
const heading = document.getElementById('title');
const paragraphs = document.querySelectorAll('p');

// Modifying content
heading.textContent = 'New Heading';
heading.style.color = 'blue';

// Creating elements
const newDiv = document.createElement('div');
document.body.appendChild(newDiv);

// Event handling
button.addEventListener('click', () => {
    console.log('Button clicked!');
});
  1. Fetch API: Purpose:

    • A modern way to make network requests

    • Replace older XMLHttpRequest

    • Promise-based asynchronous data fetching

Key Features:

  • Simple, clean syntax

  • Support for various request methods

  • Easy promise chaining

  • Built-in request/response handling

Example:

// GET Request
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

// POST Request
fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'John',
        age: 30
    })
})
  1. Geolocation API: Purpose:

  • Access the user's geographical location

  • Get latitude/longitude

  • Retrieve location details

  • Enable location-based services

Key Capabilities:

  • Get current position

  • Watch position changes

  • Handle location errors

  • Configurable accuracy

Example:

// Check if geolocation supported
if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(
        // Success callback
        (position) => {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
            console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
        },
        // Error callback
        (error) => {
            console.error("Error getting location:", error.message);
        },
        // Options
        {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        }
    );
}

// Continuous location tracking
const watchId = navigator.geolocation.watchPosition(
    (position) => {
        // Handle position updates
    },
    (error) => {
        // Handle errors
    }
);

// Stop tracking
navigator.geolocation.clearWatch(watchId);

Web Storage API Overview: Purpose:

  • Client-side data storage mechanism

  • Allows websites to store key-value pairs in browser

  • Provides two primary storage objects:

    1. localStorage

    2. sessionStorage

Key Characteristics:

  • Store data as strings

  • Synchronous API

  • Domain-specific storage

  • Simple key-value interface

  • Larger storage capacity compared to cookies

localStorage:

  • Persists data across browser sessions

  • No expiration time

  • Shared across browser tabs/windows

  • Maximum storage ~5-10MB

Example:

// Storing data
localStorage.setItem('username', 'JohnDoe');
localStorage.setItem('isLoggedIn', 'true');

// Retrieving data
const username = localStorage.getItem('username');
const loginStatus = localStorage.getItem('isLoggedIn');

// Removing specific item
localStorage.removeItem('username');

// Clear all localStorage
localStorage.clear();

sessionStorage:

  • Data persists only during a browser session

  • Data cleared when tab/window closes

  • Isolated per tab/window

  • Useful for temporary data storage

Example:

// Storing session-specific data
sessionStorage.setItem('tempCartItems', JSON.stringify([1, 2, 3]));

// Retrieving data
const cartItems = JSON.parse(sessionStorage.getItem('tempCartItems'));

Advanced Usage:

// Storing complex objects
const user = {
    name: 'John',
    age: 30,
    preferences: ['dark mode']
};

// JSON stringify to store objects
localStorage.setItem('user', JSON.stringify(user));

// Parse back to object
const storedUser = JSON.parse(localStorage.getItem('user'));

Storage Event:

  • Triggered when storage changes

  • Works across different tabs/windows

window.addEventListener('storage', (event) => {
    console.log('Storage changed:', event.key);
    console.log('Old value:', event.oldValue);
    console.log('New value:', event.newValue);
});

Security Considerations:

  • Store only non-sensitive data

  • Can be accessed by any script on same domain

  • Vulnerable to XSS attacks

  • Not encrypted by default

Use Cases:

  • User preferences

  • Theme settings

  • Shopping cart items

  • Form data

  • Caching

  • Authentication tokens (with caution)

Limitations:

  • Stores only strings

  • Limited storage space

  • Synchronous (can block main thread)

  • No built-in encryption

Comparative Analysis:

  • DOM API: Client-side manipulation

  • Fetch API: Network communication

  • Geolocation API: Location services

Use Cases:

  • DOM API: Dynamic web interfaces

  • Fetch API: Data retrieval/submission

  • Geolocation API:

    • Maps integration

    • Location-based recommendations

    • Tracking delivery services

    • Local weather information

Security Considerations:

  • Geolocation requires user permission

  • Fetch has CORS restrictions

  • DOM manipulation can be sanitized to prevent XSS

Performance Tips:

  • Minimize DOM manipulations

  • Use efficient selectors

  • Handle fetch errors gracefully

  • Request location permissions carefully

Advanced Techniques:

  • Combine APIs for rich experiences

  • Implement error handling

  • Use modern JavaScript features

Each API serves a unique purpose in web development, enabling powerful, interactive web applications by bridging browser capabilities with JavaScript functionality.