23.9 Publishing Crates to Crates.io

Crates.io is the official Rust package registry. Publishing your library crate allows others to easily use it as a dependency.

23.9.1 Prerequisites

  1. Account: Create an account on Crates.io, usually via GitHub authentication.
  2. API Token: Generate an API token in your account settings on Crates.io.
  3. Login via Cargo: Authenticate your local Cargo installation with the token:
    cargo login <your_api_token>
    # Paste the token when prompted or provide it directly (less secure)
    
    This stores the token locally (typically in ~/.cargo/credentials.toml).

23.9.2 Preparing Cargo.toml

Before publishing, ensure your Cargo.toml contains the required metadata in the [package] section:

  • name: The crate name (must be unique on Crates.io).
  • version: The initial version (e.g., "0.1.0"), following SemVer.
  • license or license-file: A valid SPDX license identifier (e.g., "MIT OR Apache-2.0") or the path to a license file.
  • description: A brief summary of the crate’s purpose.
  • At least one of documentation, homepage, or repository: Links providing more information.
  • authors, readme, keywords, categories are also highly recommended.

23.9.3 The Publishing Process

  1. Package (Optional but Recommended): Simulate the packaging process to check for errors and see exactly which files will be included:

    cargo package
    

    Cargo uses .gitignore and potentially a .cargoignore file to exclude unnecessary files. Review the generated .crate file (a compressed archive) in target/package/ if needed.

  2. Publish: Upload the crate to Crates.io:

    cargo publish
    

Once published, the specific version is permanent (though it can be “yanked”). Other users can now add your crate as a dependency:

[dependencies]
your_crate_name = "0.1.0"

23.9.4 Updating and Yanking

  • Updating: To publish a new version, increment the version field in Cargo.toml (following SemVer rules), commit changes, and run cargo publish again.
  • Yanking: If you discover a critical issue (e.g., a security vulnerability) in a published version, you can “yank” it. Yanking prevents new projects from depending on that specific version by default, but does not remove it or break existing projects that already have it in their Cargo.lock.
    # Yank version 0.1.1 of your crate
    cargo yank --vers 0.1.1 your_crate_name
    
    # Un-yank (undo a yank)
    cargo unyank --vers 0.1.1 your_crate_name
    

23.9.5 Deleting Crates

Published crate versions cannot be deleted from Crates.io to ensure builds that depend on them remain reproducible. Yanking is the standard mechanism for indicating problematic versions. In truly exceptional circumstances, you might contact the Crates.io team.