Connect to Valkey
Use the connection returned by the Console or API. It has the form valkeys://user:password@host:port/0 and should be provided to the application through VALKEY_URL.
Security rules
- Always use TLS and validate the host certificate.
- Keep the
defaultuser and password out of source code. - Never use options that disable TLS, certificate, or hostname validation.
- Reuse one connection or pool per process; do not create a new connection for every command.
- After rotation, replace the protected variable and restart workers that keep old connections.
Some libraries accept only redis:// or rediss://. Replacing valkeys:// with rediss:// changes only the scheme expected by the library; TLS remains required.
Node.js and TypeScript
Install the compatible client:
npm install iovalkeyimport Redis from 'iovalkey'
const rawUrl = process.env.VALKEY_URL
if (!rawUrl) throw new Error('VALKEY_URL is required')
const parsed = new URL(rawUrl)
if (parsed.protocol !== 'valkeys:') throw new Error('VALKEY_URL must use valkeys://')
const client = new Redis({
host: parsed.hostname,
port: Number(parsed.port),
username: decodeURIComponent(parsed.username),
password: decodeURIComponent(parsed.password),
tls: { servername: parsed.hostname },
})
await client.set('healthcheck', 'ok', 'EX', 60)
console.log(await client.get('healthcheck'))
await client.quit()Python
Install valkey-py:
python -m pip install valkeyimport os
from urllib.parse import urlparse
from valkey import Valkey
raw_url = os.environ["VALKEY_URL"]
parsed = urlparse(raw_url)
if parsed.scheme != "valkeys":
raise ValueError("VALKEY_URL must use valkeys://")
client = Valkey(
host=parsed.hostname,
port=parsed.port,
username=parsed.username,
password=parsed.password,
db=0,
ssl=True,
ssl_check_hostname=True,
decode_responses=True,
)
client.set("healthcheck", "ok", ex=60)
print(client.get("healthcheck"))
client.close()Other clients
The packages below are recommended or compatible Valkey options. In every case, extract host, port, username, and password from VALKEY_URL, enable TLS, and validate the hostname.
| Language | Installation | Client |
|---|---|---|
| Go | go get github.com/valkey-io/valkey-go | valkey-go |
| Java | io.valkey:valkey-java | valkey-java |
| PHP | composer require predis/predis | Predis |
| .NET | Valkey GLIDE package | Valkey GLIDE C# |
| Ruby | gem install redis | redis |
| Rust | cargo add redis --features tokio-native-tls-comp | redis |
Minimal Go example, adapting the scheme because valkey-go accepts rediss://:
package main
import (
"context"
"log"
"os"
"strings"
valkey "github.com/valkey-io/valkey-go"
)
func main() {
rawURL := strings.Replace(os.Getenv("VALKEY_URL"), "valkeys://", "rediss://", 1)
client, err := valkey.NewClient(valkey.MustParseURL(rawURL))
if err != nil { log.Fatal(err) }
defer client.Close()
if err := client.Do(context.Background(), client.B().Ping().Build()).Error(); err != nil { log.Fatal(err) }
}Java with valkey-java (a Jedis fork):
var uri = java.net.URI.create(System.getenv("VALKEY_URL").replaceFirst("^valkeys", "rediss"));
var credentials = uri.getUserInfo().split(":", 2);
var host = uri.getHost();
var port = uri.getPort();
var username = java.net.URLDecoder.decode(credentials[0], java.nio.charset.StandardCharsets.UTF_8);
var password = java.net.URLDecoder.decode(credentials[1], java.nio.charset.StandardCharsets.UTF_8);
var pool = new io.valkey.JedisPool(
new io.valkey.JedisPoolConfig(), host, port, 5000, username, password, 0, true);
try (var client = pool.getResource()) {
client.set("healthcheck", "ok");
System.out.println(client.get("healthcheck"));
} finally {
pool.close();
}PHP with Predis; the tls scheme keeps certificate and hostname verification enabled:
<?php
$parts = parse_url(getenv('VALKEY_URL'));
$client = new Predis\Client([
'scheme' => 'tls',
'host' => $parts['host'],
'port' => (int) $parts['port'],
'username' => rawurldecode($parts['user']),
'password' => rawurldecode($parts['pass']),
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
]);
$client->set('healthcheck', 'ok');
echo $client->get('healthcheck'), PHP_EOL;
$client->disconnect();Valkey GLIDE for .NET (do not use this client in Alpine runtimes):
var rawUrl = Environment.GetEnvironmentVariable("VALKEY_URL")
?? throw new InvalidOperationException("VALKEY_URL is required");
var uri = new Uri(rawUrl.Replace("valkeys://", "rediss://", StringComparison.Ordinal));
var credentials = uri.UserInfo.Split(':', 2);
var host = uri.Host;
var port = uri.Port;
var username = Uri.UnescapeDataString(credentials[0]);
var password = Uri.UnescapeDataString(credentials[1]);
var config = new GlideClientConfiguration {
Addresses = [new NodeAddress(host, port)],
UseTls = true,
Credentials = new ServerCredentials(username, password),
};
await using var client = await GlideClient.CreateClientAsync(config);
await client.SetAsync("healthcheck", "ok");
Console.WriteLine(await client.GetAsync("healthcheck"));Ruby with the redis gem:
require "openssl"
require "redis"
url = ENV.fetch("VALKEY_URL").sub("valkeys://", "rediss://")
client = Redis.new(url: url, ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_PEER })
client.set("healthcheck", "ok")
puts client.get("healthcheck")
client.closeRust with the redis crate and the tokio-native-tls-comp feature:
use redis::AsyncCommands;
let url = std::env::var("VALKEY_URL")?.replacen("valkeys://", "rediss://", 1);
let client = redis::Client::open(url)?;
let mut connection = client.get_multiplexed_async_connection().await?;
connection.set::<_, _, ()>("healthcheck", "ok").await?;
println!("{}", connection.get::<_, String>("healthcheck").await?);For Java, PHP, .NET, Ruby, and Rust, keep the system certificate store, use the returned hostname for SNI, and issue PING before starting a worker. Check the installed client version for constructor and option names without disabling TLS validation.
Test the connection
With valkey-cli, validation should be explicit:
valkey-cli -u "${VALKEY_URL/valkeys:/rediss:}" --tls pingThe expected response is PONG. Do not put the password directly in shell history; use your platform’s secret mechanism or VALKEYCLI_AUTH in a temporary process.