FQL v4 will be decommissioned on June 30, 2025. Ensure that you complete your migration from FQL v4 to FQL v10 by that date.

For more details, see the v4 EOL announcement and migration guide. Contact support@fauna.com with any questions.

CreateKey

This reference topic applies to FQL v4. Go to this page for the latest FQL v10 reference topics.

CreateKey( param_object )
create_key( param_object )
CreateKey( param_object )
CreateKey( param_object )
CreateKey( param_object )

Description

The CreateKey function creates a new key, based on the settings in param_object, which can be used to access the current database. If you provide an optional Reference to a child database, the key is associated with (and provides access to) that database. An admin key must be used when calling CreateKey.

Once the key is created, the key’s secret can be used to connect to Fauna and execute queries within the associated database, with the permissions associated with the key’s role.

If you would prefer to use Fauna’s Attribute-based access control (ABAC), you should use the Login function instead.

Parameters

Parameter Type Definition and Requirements

param_object

Object

The param_object fields are described below.

param_object

Field Name Field Type Definition and Requirements

role

String, Reference to a user-defined role, or an Array of user-defined role references

The built-in access roles include admin, server, server-readonly, client, or one or more user-defined roles.

database

Reference

Optional - A ref of an existing child database. If not provided, the new key grants access to the current database.

priority

Integer

Optional - A relative weight between 1 and 500, inclusive, indicating how many resources this key should be allowed to utilize. Defaults to 1. A higher number means more resources.

The priority option is deprecated as of release 2.10.0. You should avoid specifying priority. In some future Fauna release, priority will be removed. See Deprecations for more details.

data

Object

Optional - Contains user-defined metadata for the key. It is provided for the developer to store key-relevant information.

.name

String

Optional - A name to apply to the key, to help differentiate this key from any others that may exist. If provided, this field must exist within the data field.

ttl

Timestamp

Optional - A timestamp that indicates the time-to-live for a document, which is when the document is removed from the collection and can’t be queried. The document history can continue to be accessed using the Events function, provided the events are in the history retention interval and the document reference is input to the Events function.

Returns

An object containing the metadata about the results of CreateKey operations.

Field Name Field Type Definition and Requirements

ref

Reference

The Reference is an automatically-generated, unique identifier within the database to the key that was created.

database

Reference

The Reference of the database that the key belongs to.

role

String

The access role for this key.

data

Object

Returned only when provided as a CreateKey parameter, and when returned, its value is identical to the value provided.

.name

String

Returned only when provided as a CreateKey parameter, and when returned, its value is identical to the value provided.

ts

Long

The timestamp, with microsecond resolution, associated with the creation of the key.

secret

String

The key’s authentication secret. It is only present at creation. You must copy the key’s secret and store it securely for future use.

hashed_secret

String

The key’s hashed authentication secret.

Examples

The following query creates a key for the prydain database with an access role of server:

client.query(
  q.CreateKey({
    database: q.Database('prydain'),
    role: 'server',
  })
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
{
  ref: Ref(Keys(), "268220607958614528"),
  ts: 1592053954950000,
  database: Database("prydain"),
  role: 'server',
  secret: 'fnADuOk4ytACAMKkYwdY6_SYMpAit84dtYsUsXFF',
  hashed_secret: '$2a$05$7w6fYT43jPB0A.R7i8JayuTLn6kXxsL2Y5nkNjrWZurL9L9pgxo/y'
}
result = client.query(
  q.create_key({
    "database": q.database("prydain"),
    "role": "server"
  })
)
print(result)
{'ref': Ref(id=269061973282390528, collection=Ref(id=keys)), 'ts': 1592856343450000, 'database': Ref(id=prydain, collection=Ref(id=databases)), 'role': 'server', 'secret': 'fnADu-ZwbBACAGltDvSmU9jtXyMC7ccUjiKZlrhS', 'hashed_secret': '$2a$05$Vr7fLfa78XBrAKvWz4iZwezuG9l8kXII259nL6BFi0jmFkrAakrB6'}
result, err := client.Query(
	f.CreateKey(
		f.Obj{"database": f.Database("prydain"), "role": "server"}))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[database:{prydain 0xc0000af470 0xc0000af470 <nil>} hashed_secret:$2a$05$8fx.ey/kjuBqC24rJnPFeud6eJgANXrM6VCKLwkbTa/zkHq8/CUT2 ref:{280481798553600512 0xc0000af380 0xc0000af380 <nil>} role:server secret:fnAD5Hi1sMACACNy_iktsZt_JnfMqXzS2fqsF0qS ts:1603747137510000]
try
{
    Value result = await client.Query(
        CreateKey(
            Obj("database", Database("prydain"), "role", "server")
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(ref: RefV(id = "280491289873482240", collection = RefV(id = "keys")),ts: LongV(1603756189140000),database: RefV(id = "prydain", collection = RefV(id = "databases")),role: StringV(server),secret: StringV(fnAD5IFXj4ACAHEArhW3oKlskzXWbls6MrFQcyxr),hashed_secret: StringV($2a$05$G0OyeKLOQUK6zuStl6gHbulOXe6UYlCImIfh9ROp/EiX2edV6DtLa))
CreateKey({
  database: Database('prydain'),
  role: 'server',
})
{
  ref: Ref(Keys(), "302043905096942080"),
  ts: 1624310364730000,
  database: Database("prydain"),
  role: 'server',
  secret: 'fnAEMRNU1eACAAzEarJdoBSJp5w7-VrGNSXTUMBi',
  hashed_secret: '$2a$05$piVqzNsKHfKEFmivgNkhJexOVNaRxfberO1tHj.LqLow9w0ZWygtm'
}
Query metrics:
  •    bytesIn:   77

  •   bytesOut:  340

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:  153

  • writeBytes:  487

  •  queryTime: 42ms

  •    retries:    0

The following query creates a key for the current database with a user-defined role:

client.query(
  q.CreateKey({
    role: q.Role('employees'),
    data: {
      name: 'For employees',
    },
  })
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
{
  ref: Ref(Keys(), "285195918840431104"),
  ts: 1608242872990000,
  role: Role("employees"),
  data: { name: 'For employees' },
  secret: 'fnAD9TgtWeACAHKpRO6F72OxRD1dRvBLqixtBPPX',
  hashed_secret: '$2a$05$/Ft/mYSFoGkSUfOzOEmhSeDu1TSHd8TTVu0JRCemqTef8Szku3dOa'
}
result = client.query(
  q.create_key({
    "role": q.role("employees"),
    "data": {
      "name": "For employees"
    }
  })
)
print(result)
{'ref': Ref(id=285196421681906176, collection=Ref(id=keys)), 'ts': 1608243352500000, 'role': Ref(id=employees, collection=Ref(id=roles)), 'data': {'name': 'For employees'}, 'secret': 'fnAD9TiibZACAKxSQ00bgn1caRIF3fZ4SlK9bJfp', 'hashed_secret': '$2a$05$Mtghtu5ehdcFnx.jgakc/.pdZwyeeloAceC4av7svtXX/UK7gX/Ga'}
result, err := client.Query(
	f.CreateKey(
		f.Obj{
			"role": f.Role("employees"),
			"data": f.Obj{
				"name": "For employees",
			}}))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[data:map[name:For employees] hashed_secret:$2a$05$zK1Zd/fRGIFYMQq5qqPnCu85J9rhiwoC2wKG0j7BrrZvBymwJG.1W ref:{285195867337523712 0xc000146120 0xc000146120 <nil>} role:{employees 0xc000146240 0xc000146240 <nil>} secret:fnAD9TghXBACANplvoVk6GcpyoCj_-m-Dc7DP1Jr ts:1608242823840000]
try
{
    Value result = await client.Query(
        CreateKey(
            Obj(
                "role", Role("employees"),
                "data", Obj(
                    "name", "For employees"
                )
            )
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(ref: RefV(id = "285195865600033280", collection = RefV(id = "keys")),ts: LongV(1608242822180000),role: RefV(id = "employees", collection = RefV(id = "roles")),data: ObjectV(name: StringV(For employees)),secret: StringV(fnAD9Tgg9IACAKAIGxuFjqVNyQXz5MKm5SAqhJuk),hashed_secret: StringV($2a$05$vDPXveFBl5XT9tdhAIizdODVu54u07v4BsX59357o5YKiOW538J4O))
CreateKey({
  role: Role('employees'),
  data: {
    name: 'For employees',
  },
})
{
  ref: Ref(Keys(), "302043907216114176"),
  ts: 1624310366750000,
  role: Role("employees"),
  data: { name: 'For employees' },
  secret: 'fnAEMRNVVDACAFyp10FYC3DJF1fMsktMFdJBs6WM',
  hashed_secret: '$2a$05$wNXwhj6dafxwbXzxG0.LyuPqzOR9Uj4VfSosFPk5/5/u5iP8v6IPG'
}
Query metrics:
  •    bytesIn:   98

  •   bytesOut:  350

  • computeOps:    1

  •    readOps:    0

  •   writeOps:    1

  •  readBytes:  162

  • writeBytes:  364

  •  queryTime: 56ms

  •    retries:    0

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!