Authentication overview

The Netlify API provides a REST-based interface for managing sites, deployments, forms, and other platform features programmatically. Secure access to these resources requires authentication, ensuring that only authorized requests are processed. Netlify API utilizes standard web authentication mechanisms, primarily Personal Access Tokens and OAuth 2.0, to verify user and application identities. Each API request must include a valid access token in the Authorization header to be successfully processed.

Authentication protects user data and ensures that API operations adhere to the permissions granted to the specific token or application. Understanding the distinctions between these methods is important for choosing the appropriate approach for different integration scenarios, from simple command-line scripts to complex third-party applications. The API reference on Netlify's OpenAPI specification details the expected authentication headers for each endpoint.

Supported authentication methods

Netlify API supports two primary authentication methods: Personal Access Tokens (PATs) and OAuth 2.0. Each method is designed for different use cases and provides varying levels of security and control.

Personal Access Tokens (PATs)

Personal Access Tokens are long-lived tokens that grant direct access to your Netlify account on your behalf. They are suitable for:

  • Command-line tools and scripts
  • Continuous Integration/Continuous Deployment (CI/CD) pipelines
  • Personal development projects
  • Integrations where a user directly controls the access

PATs represent a user's full permissions (or a subset if scopes are implemented by Netlify for PATs, check Netlify CLI authentication documentation for current details), so they should be treated with the same care as account passwords. They are generated once and should be stored securely.

OAuth 2.0

OAuth 2.0 is an authorization framework that enables third-party applications to obtain limited access to a user's Netlify account without exposing the user's credentials. This method is ideal for:

  • Third-party applications and services that integrate with Netlify
  • Marketplace integrations
  • Multi-user applications where each user grants specific permissions
  • Scenarios requiring refresh tokens for long-term, revocable access

OAuth 2.0 involves a flow where the user is redirected to Netlify to authorize the third-party application, granting it specific permissions (scopes). The application then receives an access token and, optionally, a refresh token. The OAuth 2.0 specification outlines various grant types, with Netlify primarily using the Authorization Code grant type for web applications.

Comparison of Authentication Methods

Method When to Use Security Level (General) Credential Type
Personal Access Tokens Individual scripts, CI/CD, local development, private tools High (if stored securely), tied to user account Bearer Token
OAuth 2.0 Third-party applications, multi-user services, public integrations High (scoped, revocable, user-authorized) Bearer Token (Access Token, Refresh Token)

Getting your credentials

The process for obtaining credentials differs based on the chosen authentication method.

For Personal Access Tokens (PATs)

  1. Log in to Netlify: Access your Netlify account dashboard.
  2. Navigate to User Settings: Click on your user avatar in the top right corner and select "User settings."
  3. Go to Applications: In the left sidebar, select "Applications."
  4. Generate new token: Under the "Personal access tokens" section, click "New access token."
  5. Name your token: Provide a descriptive name for your token (e.g., "CI/CD Deployment Token") to help identify its purpose later.
  6. Generate and copy: Click "Generate token." The token will be displayed once. Copy this token immediately and store it securely, as it will not be shown again. If you lose it, you will need to generate a new one. Netlify provides more detailed instructions for setting up Netlify CLI tokens, which involves similar steps for PAT generation.

For OAuth 2.0 Applications

To use OAuth 2.0, you must register your application with Netlify:

  1. Log in to Netlify: Access your Netlify account dashboard.
  2. Navigate to User Settings: Click on your user avatar and select "User settings."
  3. Go to Applications: In the left sidebar, select "Applications."
  4. Register new OAuth application: Scroll down to the "OAuth applications" section and click "Register new OAuth application."
  5. Provide application details: You will need to provide:
    • Application Name: A user-friendly name for your application.
    • Redirect URI(s): The URL(s) where Netlify will redirect the user after they authorize your application. These must be exact matches.
    • Homepage URL: Your application's website.
    • Description: A brief description of your application.
    • Logo URL (optional): A URL to your application's logo.
  6. Retrieve Client ID and Client Secret: After registration, Netlify will provide you with a Client ID and Client Secret. The Client ID is public, but the Client Secret must be kept confidential as it identifies your application to Netlify. These are critical for initiating the OAuth flow.
  7. Implement OAuth Flow: Your application will then initiate the OAuth 2.0 Authorization Code Flow, typically involving redirecting users to Netlify's authorization endpoint, handling the callback with an authorization code, and exchanging that code for an access token and refresh token using your Client ID and Client Secret. For comprehensive guidance on OAuth 2.0 implementations, refer to resources like Google's OAuth 2.0 documentation.

Authenticated request example

Once you have obtained an access token (either a PAT or an OAuth access token), you include it in the Authorization header of your API requests as a Bearer token. This is a common practice across many RESTful APIs, as detailed by the IETF RFC 6750 for Bearer Token usage.

Using a Personal Access Token (PAT) with cURL

This example demonstrates listing Netlify sites using a Personal Access Token. Replace YOUR_NETLIFY_PAT with your actual token.

curl -X GET \ 
  'https://api.netlify.com/api/v1/sites' \ 
  -H 'Authorization: Bearer YOUR_NETLIFY_PAT' \ 
  -H 'Content-Type: application/json'

Using an OAuth Access Token with JavaScript (Fetch API)

This example shows how to make an authenticated request using an OAuth access token in a web application context. Replace YOUR_OAUTH_ACCESS_TOKEN with the token obtained through the OAuth flow.

async function listNetlifySites(accessToken) {
  try {
    const response = await fetch('https://api.netlify.com/api/v1/sites', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Netlify Sites:', data);
    return data;
  } catch (error) {
    console.error('Error fetching Netlify sites:', error);
    throw error;
  }
}

// Example usage (replace with your actual token)
// listNetlifySites('YOUR_OAUTH_ACCESS_TOKEN');

Security best practices

Adhering to security best practices is essential when handling API credentials to prevent unauthorized access to your Netlify account and data.

Token Management:

  • Store tokens securely: Never hardcode tokens directly in your application code. Use environment variables for PATs in CI/CD or local development, or a secure credential store/vault. For OAuth applications, ensure Client Secrets are stored on a secure backend server and never exposed client-side.
  • Avoid committing tokens to version control: Ensure your .gitignore or equivalent includes any files containing API tokens to prevent accidental exposure.
  • Rotate tokens regularly: Periodically generate new Personal Access Tokens and revoke old ones. For OAuth, utilize refresh tokens to obtain new access tokens without re-authenticating the user, and implement proper refresh token rotation if applicable.
  • Grant least privilege: For OAuth applications, request only the minimum necessary API scopes required for your application's functionality. This limits the potential damage if a token is compromised.
  • Revoke unused tokens: Regularly review your active Personal Access Tokens and OAuth applications in your Netlify user settings and revoke any that are no longer in use or appear suspicious.

Application Security:

  • Use HTTPS exclusively: All communication with the Netlify API must occur over HTTPS to encrypt data in transit and protect tokens from interception. Netlify API enforces HTTPS.
  • Validate redirect URIs (OAuth): For OAuth applications, ensure that your registered Redirect URIs are specific and secure. Only allow redirects to URIs that you control and are secured with HTTPS.
  • Implement cross-site request forgery (CSRF) protection (OAuth): When using the OAuth Authorization Code flow, include a unique, unguessable state parameter in the authorization request and verify it upon callback to mitigate CSRF attacks.
  • Error handling: Implement robust error handling for authentication failures. Avoid returning verbose error messages that could leak sensitive information.
  • Monitor API activity: Regularly review Netlify's audit logs or integrate with an API monitoring solution to detect unusual activity that could indicate a compromised token or unauthorized access.

General Security Practices:

  • Keep dependencies updated: Ensure all libraries and frameworks used in your application are kept up to date to patch known vulnerabilities that could affect token security.
  • Follow secure coding guidelines: Adhere to secure coding principles to prevent common vulnerabilities like injection attacks that could expose credentials. Guidelines from organizations like the OWASP Top Ten provide a framework for web application security.