# jwt-encode()

```
string jwt-encode((string|OXN-node-set) jwt, string key [, number time-to-live[, string algorithm]])
```

packs and signs a *JSON web token* (JWT) as *JSON web signature* (JWS) in *compact serialization*. \[[RFC 7519](https://tools.ietf.org/html/rfc7519), [RFC 7515](https://tools.ietf.org/html/rfc7515)]

## Parameters

`data`: The payload can be provided as a JSON string or [OXN](/flat/reference/templating/oxn.md).

`key`: For the HMAC algorithms, a Base64URL encoded symmetric key for the digital signature. For the `RSASSA` based algorithms, use the PEM encoded *private* key (without the `BEGIN` and `END` lines and without any line breaks). The key must not be password protected.

`time-to-live`: Sets the time span in seconds until expiration in the `exp` claim of the `jwt`. If the TTL is `0`, no `exp` claim is added to the token – it is valid forever. Default: `0` (no expiration).

`algorithm`: The signature or HMAC algorithm to use.

Supported values:

* `HS256`
* `HS384`
* `HS512`
* `RS256`
* `RS384`
* `RS512`

Defaults to `HS256`. Consult [RFC 7518, section 3.1](https://www.rfc-editor.org/rfc/rfc7518.html#section-3.1) for an explanation of the individual values.

The return value is a *JWS compact serialization* as a string:

```
eyJ….….…
```

An empty string or false will be returned if any errors occur.

## Example

The variable `$json` contains the JSON web token to be packed, the key is read from the environment variable `$JWT_SECRET`. The encoded token is stored in the variable `$jws`. After 600 seconds the token becomes invalid:

```markup
<template out="$jws">
{{ jwt-encode($json, $env/JWT_SECRET, 600) }}
</template>
```

## See also

* [`jwt-decode()`](/flat/reference/functions/jwt-decode.md) (reference)
* [Encoding and Decoding JWT](/flat/cookbook/jwt.md) (cookbook)
* [Protecting Access using JWT Tokens](/flat/cookbook/x-flat-jwt.md) (cookbook)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sevenval.gitbook.io/flat/reference/functions/jwt-encode.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
