writeKeyPair

function writeKeyPair(keyPair, path, config?): Promise<void>;

Writes an extractable CryptoKeyPair to disk as a JSON array of 64 bytes, matching the format produced by solana-keygen. The first 32 bytes are the raw Ed25519 seed (private key) and the last 32 bytes are the raw public key.

Any missing parent directories are created automatically. The written file uses mode 0600 (owner read/write only) to match solana-keygen.

This helper requires a writable filesystem and will throw in environments that don't provide one (such as browsers or React Native).

Parameters

ParameterTypeDescription
keyPairCryptoKeyPairAn extractable CryptoKeyPair. Both the private and public keys must have been created with extractable: true.
pathstringThe destination path on disk.
config?Readonly<{ unsafelyOverwriteExistingKeyPair?: boolean; }>See WriteKeyPairConfig.

Returns

Promise<void>

Throws

A SolanaError of code `SOLANA_ERROR__KEYS__WRITE_KEY_PAIR_UNSUPPORTED_ENVIRONMENT` when called in an environment without a writable filesystem.

Throws

A SolanaError of code `SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY` when either the private or public key is not extractable.

Examples

import { generateKeyPair, writeKeyPair } from '@solana/keys';
 
// Generate an extractable key pair so its bytes can be persisted.
const keyPair = await generateKeyPair(true);
await writeKeyPair(keyPair, './my-keypair.json');

Overwriting an existing file requires an explicit opt-in, because doing so permanently destroys the previous key and any funds controlled by it:

import { writeKeyPair } from '@solana/keys';
 
await writeKeyPair(keyPair, './my-keypair.json', {
    unsafelyOverwriteExistingKeyPair: true,
});

See

On this page