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

# SETNX

> Set value if key doesn't exist.

<Warning>
  Prefer [`SET`](/docs/redis/commands/string/set) with the `NX` argument in new code: `SET <key> <value> NX`.
</Warning>

Use `SETNX` to set a value only if the key does not already exist.

The reply is `1` when the key was created and `0` when it was already there and nothing was written. The check and the write are atomic, so exactly one of several racing clients succeeds.

That makes it the classic lock primitive, but on its own it is an incomplete one: a client that fails after acquiring leaves the key behind forever. Prefer `SET key value NX EX <ttl>`, which claims the key and attaches an expiration in the same step, and release the lock with [`DELEX`](/docs/redis/commands/string/delex) so you only delete it while you still own it.

## Syntax

```redis theme={"system"}
SETNX <key> <value>
```

## Arguments

| Argument  | Required | Repeatable | Description                        |
| --------- | -------- | ---------- | ---------------------------------- |
| `<key>`   | Yes      | No         | Redis key targeted by the command. |
| `<value>` | Yes      | No         | String value to store.             |

## Response

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

| Protocol | Reply                                                     |
| -------- | --------------------------------------------------------- |
| RESP2    | Integer: `1` if the key was set, `0` if it already exists |
| RESP3    | Integer: `1` if the key was set, `0` if it already exists |

<Note>
  Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.
</Note>

## Examples

TCP examples use the TLS `REDIS_URL` from the Upstash console. REST examples use `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.

<AccordionGroup>
  <Accordion title="Redis CLI" icon="terminal">
    ```bash theme={"system"}
    SETNX my-key value
    ```
  </Accordion>

  <Accordion title="@upstash/redis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import { Redis } from "@upstash/redis";

    const redis = Redis.fromEnv();
    const result = await redis.setnx("my-key", "value");
    console.log(result);
    ```
  </Accordion>

  <Accordion title="upstash_redis" icon="python" iconType="brands">
    ```python theme={"system"}
    from upstash_redis import Redis

    redis = Redis.from_env()
    result = redis.setnx("my-key", "value")
    print(result)
    ```
  </Accordion>

  <Accordion title="ioredis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import Redis from "ioredis";

    const redis = new Redis(process.env.REDIS_URL!);
    const result = await redis.setnx("my-key", "value");
    console.log(result);
    ```
  </Accordion>

  <Accordion title="node-redis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import { createClient } from "redis";

    const client = await createClient({ url: process.env.REDIS_URL })
      .on("error", console.error)
      .connect();
    const result = await client.setNX("my-key", "value");
    console.log(result);
    ```
  </Accordion>

  <Accordion title="redis-py" icon="python" iconType="brands">
    ```python theme={"system"}
    import os
    import redis

    client = redis.from_url(os.environ["REDIS_URL"])
    result = client.setnx("my-key", "value")
    print(result)
    ```
  </Accordion>

  <Accordion title="go-redis" icon="golang" iconType="brands">
    ```go theme={"system"}
    package main

    import (
        "context"
        "fmt"
        "os"

        "github.com/redis/go-redis/v9"
    )

    func main() {
        opts, err := redis.ParseURL(os.Getenv("REDIS_URL"))
        if err != nil {
            panic(err)
        }
        client := redis.NewClient(opts)
        result, err := client.SetNX(context.Background(), "my-key", "value", 0).Result()
        if err != nil {
            panic(err)
        }
        fmt.Println(result)
    }
    ```
  </Accordion>

  <Accordion title="jedis" icon="java" iconType="brands">
    ```java theme={"system"}
    import java.net.URI;

    import redis.clients.jedis.Jedis;

    try (Jedis jedis = new Jedis(new URI(System.getenv("REDIS_URL")))) {
      Object result = jedis.setnx("my-key", "value");
      System.out.println(result);
    }
    ```
  </Accordion>

  <Accordion title="redis-rs" icon="rust" iconType="brands">
    ```rust theme={"system"}
    use redis::TypedCommands;

    fn main() -> redis::RedisResult<()> {
        let url = std::env::var("REDIS_URL").expect("REDIS_URL is not set");
        let client = redis::Client::open(url)?;
        let mut connection = client.get_connection()?;

        let result = connection.set_nx("my-key", "value")?;
        println!("{result:?}");
        Ok(())
    }
    ```
  </Accordion>
</AccordionGroup>
