> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Load a local json file keypair

> Learn how to load a keypair from file.

When running your local project, you may sometimes want to use a local keypair.
The default keypair path generated by the Solana CLI is
`~/.config/solana/id.json`.

You can generate a custom keypair using the Solana CLI command
`solana-keygen grind --starts-with hi:1`. This will generate a keypair
with a public key starting with "hi" and output the keypair to a json file. You
can then load this keypair using the helper function below.

<CodeGroup>

```ts Kit
import {
  airdropFactory,
  createKeyPairSignerFromBytes,
  createSolanaRpc,
  createSolanaRpcSubscriptions,
  generateKeyPair,
  getAddressFromPublicKey,
  type KeyPairSigner,
  lamports,
} from "@solana/kit";
import fs from "fs";
import path from "path";
import os from "os";

// The new library takes a brand-new approach to Solana key pairs and addresses,
// which will feel quite different from the classes PublicKey and Keypair from version 1.x.
// All key operations now use the native Ed25519 implementation in JavaScript's
// Web Crypto API.
async function createKeypair() {
  const newKeypair = await generateKeyPair();
  const publicAddress = await getAddressFromPublicKey(newKeypair.publicKey);

  console.log(`Public key: ${publicAddress}`);
}

await createKeypair();

export async function loadKeypairFromFile(
  filePath: string,
): Promise<KeyPairSigner<string>> {
  // This is here so you can also load the default keypair from the file system.
  const resolvedPath = path.resolve(
    filePath.startsWith("~") ? filePath.replace("~", os.homedir()) : filePath,
  );
  const loadedKeyBytes = Uint8Array.from(
    JSON.parse(fs.readFileSync(resolvedPath, "utf8")),
  );
  // Here you can also set the second parameter to true in case you need to extract your private key.
  const keypairSigner = await createKeyPairSignerFromBytes(loadedKeyBytes);
  return keypairSigner;
}

const keypairSigner = await loadKeypairFromFile("~/.config/solana/id.json");
console.log(keypairSigner.address);

export async function loadDefaultKeypair(): Promise<KeyPairSigner<string>> {
  return await loadKeypairFromFile("~/.config/solana/id.json");
}

const defaultSigner = await loadDefaultKeypair();
console.log(defaultSigner.address);

export async function loadDefaultKeypairWithAirdrop(
  rpcUrl: string,
  rpcSubscriptionsUrl: string,
): Promise<KeyPairSigner<string>> {
  const keypair = await loadDefaultKeypair();
  const rpc = createSolanaRpc(rpcUrl);
  const rpcSubscriptions = createSolanaRpcSubscriptions(rpcSubscriptionsUrl);
  try {
    const result = await rpc.getBalance(keypair.address).send();

    console.log(`Balance: ${result.value} lamports`);
    if (result.value < lamports(500_000n)) {
      console.log(`Balance low requesting airdrop`);
      const airdrop = airdropFactory({ rpc, rpcSubscriptions });
      await airdrop({
        commitment: "confirmed",
        lamports: lamports(1_000_000_000n),
        recipientAddress: keypair.address,
      });
    }
  } catch (err) {
    console.error("Error fetching balance:", err);
  }
  return keypair;
}

const airdropSigner = await loadDefaultKeypairWithAirdrop(
  "http://localhost:8899",
  "ws://localhost:8900",
);
console.log(airdropSigner.address);
```

```ts title="Web3.js v3"
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import { readFileSync } from "fs";
import { homedir } from "os";
import path from "path";

export async function loadKeypairFromFile(filePath: string): Promise<Keypair> {
  const resolvedPath = path.resolve(
    filePath.startsWith("~") ? filePath.replace("~", homedir()) : filePath,
  );
  const loadedKeyBytes = Uint8Array.from(
    JSON.parse(readFileSync(resolvedPath, "utf8")),
  );
  return Keypair.fromSecretKey(loadedKeyBytes);
}

const keypair = await loadKeypairFromFile("~/.config/solana/id.json");
console.log(keypair.publicKey.toBase58());

export async function loadDefaultKeypair(): Promise<Keypair> {
  return await loadKeypairFromFile("~/.config/solana/id.json");
}

const defaultKeypair = await loadDefaultKeypair();
console.log(defaultKeypair.publicKey.toBase58());

export async function loadDefaultKeypairWithAirdrop(
  rpcUrl: string,
): Promise<Keypair> {
  const keypair = await loadDefaultKeypair();
  const connection = new Connection(rpcUrl, "finalized");

  try {
    const balance = await connection.getBalance(keypair.publicKey);

    console.log(`Balance: ${balance} lamports`);
    if (balance < 0.05 * LAMPORTS_PER_SOL) {
      console.log(`Balance low requesting airdrop`);
      await connection.requestAirdrop(keypair.publicKey, 1_000_000_000);
    }
  } catch (err) {
    console.error("Error fetching balance:", err);
  }
  return keypair;
}

const airdropKeypair = await loadDefaultKeypairWithAirdrop(
  "http://localhost:8899",
);
console.log(airdropKeypair.publicKey.toBase58());
```

```rust Rust
use solana_sdk::signer::{
    keypair::{self, Keypair},
    Signer,
};
use std::{env, path};

fn load_default_keypair() -> anyhow::Result<Keypair> {
    let home_path = env::var_os("HOME").unwrap();
    let default_keypair_path = ".config/solana/id.json"; // ! update if you want to use a different path
    let default_keypair_path = path::PathBuf::from(home_path).join(default_keypair_path);

    let default_keypair =
        keypair::read_keypair_file(default_keypair_path).expect("error reading keypair from path");

    println!("loaded keypair address -> {:?}", default_keypair.pubkey());

    Ok(default_keypair)
}
```

```py Python
from pathlib import Path

from solders.keypair import Keypair

keypair_path = Path.home() / ".config" / "solana" / "id.json"
keypair = Keypair.from_json(keypair_path.read_text())

print(keypair.pubkey())
```

```go Go
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/solana-foundation/solana-go/v2"
)

func main() {
	home, err := os.UserHomeDir()
	if err != nil {
		panic(err)
	}
	keypair, err := solana.PrivateKeyFromSolanaKeygenFile(filepath.Join(home, ".config", "solana", "id.json"))
	if err != nil {
		panic(err)
	}

	fmt.Println(keypair.PublicKey())
}
```

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

```ts title="Web3.js (legacy)"
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import { readFileSync } from "fs";
import { homedir } from "os";
import path from "path";

export async function loadKeypairFromFile(filePath: string): Promise<Keypair> {
  const resolvedPath = path.resolve(
    filePath.startsWith("~") ? filePath.replace("~", homedir()) : filePath,
  );
  const loadedKeyBytes = Uint8Array.from(
    JSON.parse(readFileSync(resolvedPath, "utf8")),
  );
  return Keypair.fromSecretKey(loadedKeyBytes);
}

const keypair = await loadKeypairFromFile("~/.config/solana/id.json");
console.log(keypair.publicKey.toBase58());

export async function loadDefaultKeypair(): Promise<Keypair> {
  return await loadKeypairFromFile("~/.config/solana/id.json");
}

const defaultKeypair = await loadDefaultKeypair();
console.log(defaultKeypair.publicKey.toBase58());

export async function loadDefaultKeypairWithAirdrop(
  rpcUrl: string,
): Promise<Keypair> {
  const keypair = await loadDefaultKeypair();
  const connection = new Connection(rpcUrl, "finalized");

  try {
    const balance = await connection.getBalance(keypair.publicKey);

    console.log(`Balance: ${balance} lamports`);
    if (balance < 0.05 * LAMPORTS_PER_SOL) {
      console.log(`Balance low requesting airdrop`);
      await connection.requestAirdrop(keypair.publicKey, 1_000_000_000);
    }
  } catch (err) {
    console.error("Error fetching balance:", err);
  }
  return keypair;
}

const airdropKeypair = await loadDefaultKeypairWithAirdrop(
  "http://localhost:8899",
);
console.log(airdropKeypair.publicKey.toBase58());
```

</CodeGroup>
