Getting started overview

CDNJS facilitates the delivery of popular open-source JavaScript libraries, CSS frameworks, and fonts directly to web projects via a global Content Delivery Network. Unlike many API services, CDNJS does not require an account, API keys, or a complex authentication flow for its primary function: serving static assets.

The core interaction involves searching for a desired library on the CDNJS website, selecting a specific version, and then copying the generated HTML <script> or <link> tag. This tag is then embedded into your web page, allowing browsers to fetch the asset directly from CDNJS's distributed servers.

For developers requiring programmatic access to library data, such as fetching lists of available libraries, versions, or file paths, CDNJS provides a public API. This API also does not require authentication, simplifying integration into build tools or custom applications. The API uses a RESTful architecture, typically returning JSON responses.

The process of integrating CDNJS assets into a web project is summarized in the following steps:

Step What to Do Where
1. Find Library Search for the desired JavaScript, CSS, or font library. CDNJS website library search
2. Select Version Choose the specific version and desired file(s) for the library. CDNJS library version selection
3. Copy Tag Copy the generated HTML <script> or <link> tag. CDNJS file URL and tag generation
4. Embed Tag Paste the copied tag into your HTML file (typically in the <head> for CSS or before </body> for JavaScript). Your web project's HTML file
5. Verify Integration Open your web page in a browser and check the developer console for loaded assets and functionality. Browser developer tools

Create an account and get keys

For the primary use case of serving open-source libraries through its Content Delivery Network, CDNJS does not require users to create an account or obtain API keys. This design choice simplifies the integration process, allowing developers to immediately incorporate libraries into their projects without registration overhead. Users can directly visit the CDNJS website, search for a library, and copy the necessary HTML tags.

The absence of an account or key requirement extends to the CDNJS API for programmatic access. Developers can query the API endpoints directly from their applications or build scripts to retrieve library information, such as available versions, file listings, and metadata, without any authentication headers or tokens. This open access model aligns with CDNJS's mission to provide free and accessible open-source assets globally.

This approach contrasts with many commercial API providers, such as Stripe's API documentation or Cloudflare's getting started guides for their API, which typically mandate account creation and API key generation for security, rate limiting, and billing purposes. CDNJS, being a community-driven, free service, operates under a different operational model where direct access is prioritized over individual user management.

Therefore, if your goal is to simply include a JavaScript library like jQuery or a CSS framework like Bootstrap in your web project, you can proceed directly to the "Your first request" section without any prior setup steps involving accounts or credentials.

Your first request

A "first request" with CDNJS typically refers to successfully linking an external asset in your HTML that is then served by the CDN. There are two primary methods: direct HTML embedding or programmatic API interaction.

Direct HTML Embedding (Most Common Use)

This method involves finding the desired library on the CDNJS website and embedding its generated URL into your web page. For example, to include the popular JavaScript library jQuery, follow these steps:

  1. Navigate to the CDNJS website.
  2. Use the search bar to find "jQuery".
  3. On the jQuery library page, you will see a list of available versions and files. Select the latest stable version (e.g., 3.7.1).
  4. Locate the desired file, typically the minified version (e.g., jquery.min.js).
  5. Click the "Copy Script Tag" button next to the file. This copies an HTML <script> tag to your clipboard.

The copied tag will resemble this (version numbers may vary):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Now, open your HTML file (e.g., index.html) and paste this tag. For JavaScript libraries, it's generally best practice to place the script tag just before the closing </body> tag to ensure the DOM is fully loaded before the script executes, preventing render-blocking. For CSS files, place the <link> tag within the <head> section.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My CDNJS Test Page</title>
    <!-- Example for CSS: Bootstrap -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
    <h1>Hello from CDNJS!</h1>
    <p>This page uses jQuery and Bootstrap from CDNJS.</p>

    <script>
        // Your custom JavaScript code here
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM is ready.');
            // Example of using jQuery from CDNJS
            if (typeof jQuery !== 'undefined') {
                console.log('jQuery is loaded, version:', jQuery.fn.jquery);
                $('h1').text('jQuery Loaded Successfully!');
            } else {
                console.log('jQuery not loaded.');
            }
        });
    </script>
    
    <!-- The jQuery script tag from CDNJS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <!-- Example for JS: Bootstrap bundle -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/js/bootstrap.bundle.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

</body>
</html>

Save your HTML file and open it in a web browser. Inspect the browser's developer console (usually F12 or Cmd+Option+I) under the "Network" tab. You should see requests for jquery.min.js (and potentially bootstrap.min.css and bootstrap.bundle.min.js) with a status code of 200 OK, indicating successful retrieval from the CDN. In the "Console" tab, you should see the "jQuery Loaded Successfully!" message.

Programmatic API Request

For developers building tools or requiring dynamic access to library data, the CDNJS API provides a way to fetch information. For instance, to get a list of all libraries, you can make a simple HTTP GET request to the main API endpoint.

curl -X GET "https://api.cdnjs.com/libraries"

This curl command will return a JSON object containing a list of libraries, each with details such as name, description, and latest version. For a more focused query, you can search for a specific library:

curl -X GET "https://api.cdnjs.com/libraries?search=react"

This request would return information about libraries matching "react", such as React itself. The CDNJS API documentation provides further details on available parameters for filtering and retrieving specific library versions or file paths.

Common next steps

Once you have successfully integrated a CDNJS asset into your project, several common next steps can enhance your development workflow and project performance:

  • Version Management: While using the latest version is often desirable, consider fixing the version number in your URLs (e.g., 3.7.1 instead of 3) for production environments to prevent unexpected breaking changes if a new major version is released. CDNJS URLs like /ajax/libs/jquery/3.7.1/jquery.min.js are immutable for a specific version, ensuring stability.
  • Integrate More Libraries: Explore the vast collection of libraries available on CDNJS for other project needs, such as animation libraries (e.g., Animate.css), charting libraries (e.g., Chart.js), or utility libraries (e.g., Lodash).
  • Subresource Integrity (SRI): For enhanced security, CDNJS provides Subresource Integrity (SRI) hashes with its generated script and link tags. SRI allows browsers to verify that fetched resources have not been tampered with. Always include the integrity and crossorigin attributes when embedding CDNJS resources in production environments. An example can be found in the W3C Subresource Integrity specification.
  • Local Fallbacks: Implement local fallbacks for critical assets. In rare cases where the CDN might be unavailable or blocked, a local copy of the library can be served. This typically involves a check in JavaScript to see if the CDN-loaded library is available, and if not, dynamically appending a script tag for a local copy.
  • Caching Strategies: Understand how browsers cache CDN resources. Because CDNJS uses aggressive caching headers, the browser will store the asset for a specified duration, improving performance on subsequent visits.
  • Explore the API: If you're building a content management system, a build tool, or need to dynamically fetch library information, explore the CDNJS API. You can use it to programmatically search for libraries, retrieve file listings, and gather metadata, which can be useful for automating asset management.
  • Contribution: CDNJS is an open-source project. If you find a library missing or want to contribute to its maintenance, consider checking out the contribution guidelines.

Troubleshooting the first call

If your CDNJS asset isn't loading as expected, here are common troubleshooting steps:

  • Check Network Tab in Developer Tools: Open your browser's developer tools (F12 or Cmd+Option+I), navigate to the "Network" tab, and reload the page. Look for the specific CDNJS URL you've included (e.g., jquery.min.js).
    • 404 Not Found: This usually means the URL is incorrect. Double-check the path, file name, and version number. Ensure there aren't any typos. Verify the exact URL on the CDNJS website.
    • Blocked/CORS Errors: If you see red error messages related to CORS (Cross-Origin Resource Sharing) or a blocked request, ensure the crossorigin="anonymous" and referrerpolicy="no-referrer" attributes are present in your <script> or <link> tag. CDNJS provides these by default when you copy the tags. These attributes are standard for resources loaded from different origins and are required for features like Subresource Integrity.
    • Pending/Stalled: If the request is stuck in a "pending" state, it might indicate a network issue, ad blocker interference, or a problem with the CDN itself (rare). Try disabling browser extensions or testing on a different network.
  • Check Console Tab for JavaScript Errors: If a JavaScript library fails to load or execute, it might generate an error in the "Console" tab. Look for messages like "Uncaught ReferenceError: $ is not defined" (for jQuery), which suggests the script either didn't load or loaded incorrectly.
    • Script Order: Ensure dependent scripts are loaded after their dependencies. For example, any custom JavaScript code that uses jQuery must be placed after the jQuery script tag.
  • Subresource Integrity (SRI) Mismatch: If you've included the integrity attribute and the resource has been tampered with or corrupted, the browser will block its execution and report an SRI error in the console. Verify that the integrity hash matches the one provided by CDNJS for the exact file and version. If you manually modified the file path or version, the hash will become invalid.
  • Browser Cache: Sometimes, stale browser cache can cause issues. Perform a hard refresh (Ctrl+Shift+R or Cmd+Shift+R) or clear your browser's cache for the problematic domain.
  • CDNJS Status: While rare, check the CDNJS status page or their social media channels for any reported outages or issues that might affect service delivery. CDNJS utilizes Cloudflare's network, so reviewing Cloudflare's status page can also provide relevant information.
  • Ad Blockers/Security Software: Some aggressive ad blockers or enterprise security software can block CDN requests. Temporarily disable them for testing purposes to rule them out as the cause.
  • Syntax Errors in HTML: A malformed HTML tag (e.g., missing closing quote, incorrect attribute) can prevent the browser from correctly parsing the script or link tag. Use an HTML validator if necessary.