> This is the guide on how to configure **Unleash v4 self-hosted**. If you are still using Unleash v3 you should checkout [configuring Unleash v3](./configuring-unleash-v3.md)
In order for Unleash server to work, you need a running database and its connection details. See the [database configuration section](#database-configuration) for the available options and configuration details.
- Configured with `UNLEASH_URL`** Should be set to the public discoverable URL of your instance, so if your instance is accessed by your users at `https://unleash.mysite.com` use that. ** If you're deploying this to a subpath, include the subpath in this. So `https://mysite.com/unleash` will also be correct.
Used to send reset-password mails and welcome mails when onboarding new users. <br/>**NOTE** - If this is not configured, you will not be able to allow your users to reset their own passwords.
In order to customize "anything" in Unleash you need to use [Unleash from Node.js](./getting-started.md#option-two---from-nodejs) or start the [docker image](./getting-started.md#option-one---use-docker) with environment variables.
-`none` - _Deprecated_ Turn off authentication completely. If no API token is provided towards /`api/client` or `/api/frontend` you will receive configuration for the "default" environment. We generally recommend you use the `demo` type for simple, insecure usage of Unleash. This auth type has many known limitations, particularly related to personalized capabilities such as favorites and [notifications](../../reference/notifications.md).
-`customAuthHandler`: function `(app: any, config: IUnleashConfig): void` — custom express middleware handling authentication. Used when type is set to `custom`. Can not be set via environment variables.
-`initialAdminUser`: `{ username: string, password: string} | null` — whether to create an admin user with default password - Defaults to using `admin` and `unleash4all` as the username and password. Can not be overridden by setting the `UNLEASH_DEFAULT_ADMIN_USERNAME` and `UNLEASH_DEFAULT_ADMIN_PASSWORD` environment variables.
-`initApiTokens` / `INIT_ADMIN_API_TOKENS`, `INIT_CLIENT_API_TOKENS`, and `INIT_FRONTEND_API_TOKENS`: `ApiTokens[]` — Array of API tokens to create on startup. The tokens will only be created if the database doesn't already contain any API tokens. Example:
The tokens can be of any API token type. Note that _admin_ tokens **must** target all environments and projects (i.e. use `'*'` for `environments` and `project` and start the secret with `*:*.`).
You can also use the environment variables `INIT_ADMIN_API_TOKENS`, `INIT_CLIENT_API_TOKENS`, and `INIT_FRONTEND_API_TOKENS`. All variables require a comma-separated list of API tokens to initialize (for instance `*:*.some-random-string, *:*.some-other-token`). The tokens found in `INIT_ADMIN_API_TOKENS`, `INIT_CLIENT_API_TOKENS`, and `INIT_FRONTEND_API_TOKENS` will be created as admin, client, and frontend tokens respectively, and Unleash will assign usernames automatically.
- **databaseUrl** - (_deprecated_) the postgres database url to connect to. Only used if _db_ object is not specified, and overrides the _db_ object and any environment variables that change parts of it (like `DATABASE_SSL`). Should include username/password. This value may also be set via the `DATABASE_URL` environment variable. Alternatively, if you would like to read the database url from a file, you may set the `DATABASE_URL_FILE` environment variable with the full file path. The contents of the file must be the database url exactly.
- **db** - The database configuration object. See [the database configuration section](#database-configuration) for a full overview of the available properties.
- **disableLegacyFeaturesApi** (boolean) - whether to disable the [legacy features API](/reference/api/legacy/unleash/admin/features.md). Defaults to `false` (`DISABLE_LEGACY_FEATURES_API`). Introduced in Unleash 4.6.
- ~~eventHook~~ (`function(event, data)`) - (_deprecated in Unleash 4.3_ in favor of the [Webhook integration](/reference/integrations/webhook.md). **Removed in Unleash 5**) If provided, this function will be invoked whenever a feature is mutated. The possible values for `event` are `'feature-created'`, `'feature-archived'` and `'feature-revived'`. The `data` argument contains information about the mutation. Its fields are `type` (string) - the event type (same as `event`); `createdBy` (string) - the user who performed the mutation; `data` - the contents of the change. The contents in `data` differs based on the event type; For `'feature-archived'` and `'feature-revived'`, the only field will be `name` - the name of the feature. For `'feature-created'` the data follows a schema defined in the code [here](https://github.com/Unleash/unleash/blob/7b7f0b84e8cddd5880dcf29c231672113224b9a7/src/lib/schema/feature-schema.ts#L77). See an [api here](/reference/api/legacy/unleash/admin/events).
- **preHook** (function) - this is a hook if you need to provide any middlewares to express before `unleash` adds any. Express app instance is injected as first argument.
- **preRouterHook** (function) - use this to register custom express middlewares before the `unleash` specific routers are added.
- **secureHeaders** (boolean) - use this to enable security headers (HSTS, CSP, etc) when serving Unleash from HTTPS. Can also be configured through the environment variable `SECURE_HEADERS`.
- **additionalCspAllowedDomains** (CspAllowedDomains) - use this when you want to enable security headers but have additional domains you need to allow traffic to. You can set the following environment variables:
- **server** - The server config object taking the following properties
- _port_ - which port the unleash-server should bind to. If port is omitted or is 0, the operating system will assign an arbitrary unused port. Will be ignored if pipe is specified. This value may also be set via the `HTTP_PORT` environment variable
- _host_ - which host the unleash-server should bind to. If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. This value may also be set via the `HTTP_HOST` environment variable
- _pipe_ - parameter to identify IPC endpoints. See https://nodejs.org/api/net.html#net_identifying_paths_for_ipc_connections for more details
- _serverMetrics_ (boolean) - use this option to turn on/off prometheus metrics.
- _baseUriPath_ (string) - use to register a base path for all routes on the application. For example `/my/unleash/base` (note the starting /). Defaults to `/`. Can also be configured through the environment variable `BASE_URI_PATH`.
- _unleashUrl_ (string) - Used to specify the official URL this instance of Unleash can be accessed at for an end user. Can also be configured through the environment variable `UNLEASH_URL`.
- _gracefulShutdownEnable_: (boolean) - Used to control if Unleash should shutdown gracefully (close connections, stop tasks,). Defaults to true. `GRACEFUL_SHUTDOWN_ENABLE`
- _gracefulShutdownTimeout_: (number) - Used to control the timeout, in milliseconds, for shutdown Unleash gracefully. Will kill all connections regardless if this timeout is exceeded. Defaults to 1000ms `GRACEFUL_SHUTDOWN_TIMEOUT`
- **session** - The session config object takes the following options:
- _ttlHours_ (number) - The number of hours a user session is allowed to live before a new sign-in is required. Defaults to 48 hours. `SESSION_TTL_HOURS`
- _clearSiteDataOnLogout_ (boolean) - When `true`, a logout action will return a Clear Site Data response header instructing the browser to clear all cookies on the same domain Unleash is running on. If disabled unleash will only destroy and clear the session cookie. Defaults to _true_. `SESSION_CLEAR_SITE_DATA_ON_LOGOUT`
- _cookieName_ - Name of the cookies used to hold the session id. Defaults to 'unleash-session'.
- **ui** (object) - Set of UI specific overrides. You may set the following keys: `environment`, `slogan`.
- **versionCheck** - the object deciding where to check for latest version
-`url` - The url to check version (Defaults to `https://version.unleash.run`) - Overridable with (`UNLEASH_VERSION_URL`)
-`enable` - Whether version checking is enabled (defaults to true) - Overridable with (`CHECK_VERSION`) (if anything other than `true`, does not check)
- **environmentEnableOverrides** - A list of environment names to force enable at startup. This is feature should be used with caution. When passed a list, this will enable each environment in that list and disable all other environments. You can't use this to disable all environments, passing an empty list will do nothing. If one of the given environments is not already enabled on startup then it will also enable projects and toggles for that environment. Note that if one of the passed environments doesn't already exist this will do nothing aside from log a warning.
- **clientFeatureCaching** - configuring memoization of the /api/client/features endpoint
-`enabled` - set to true by default - Overridable with (`CLIENT_FEATURE_CACHING_ENABLED`)
-`maxAge` - the time to cache features, set to 600 milliseconds by default - Overridable with (`CLIENT_FEATURE_CACHING_MAXAGE`) ) (accepts milliseconds)
-`refreshIntervalInMs` - how often (in milliseconds) front-end clients should refresh their data from the cache. Overridable with the `FRONTEND_API_REFRESH_INTERVAL_MS` environment variable.
- **accessControlMaxAge** - You can configure the max-age of the Access-Control-Max-Age header. Defaults to 86400 seconds. Overridable with the `ACCESS_CONTROL_MAX_AGE` environment variable.
- **responseTimeWithAppNameKillSwitch** - use this to disable metrics with app names. This is enabled by default but may increase the cardinality of metrics causing Unleash memory usage to grow if your app name is randomly generated (which is not recommended). Overridable with the `UNLEASH_RESPONSE_TIME_WITH_APP_NAME_KILL_SWITCH` environment variable.
- **disableCompression** - Disables Express compression middleware, useful when configuring the application in a serverless environment. Defaults to `false`. Overridable with the `SERVER_DISABLE_COMPRESSION` environment variable.
- **keepAliveTimeout** - Use this to tweak connection keepalive timeout in seconds. Useful for hosted situations where you need to make sure your connections are closed before terminating the instance. Defaults to `15`. Overridable with the `SERVER_KEEPALIVE_TIMEOUT` environment variable.
- **metricsRateLimiting** - Use the following to tweak the rate limits for `/api/client/register`, `/api/client/metrics`, `/api/frontend/register` and `/api/frontend/metrics` POST endpoints
-`clientMetricsMaxPerMinute` - How many requests per minute per IP is allowed against POST `/api/client/metrics` before returning 429. Set to 6000 by default (100rps) - Overridable with `REGISTER_CLIENT_RATE_LIMIT_PER_MINUTE` environment variable
-`clientRegisterMaxPerMinute` - How many requests per minute per IP is allowed against POST `/api/client/register` before returning 429. Set to 6000 by default (100rps) - Overridable with `CLIENT_METRICS_RATE_LIMIT_PER_MINUTE` environment variable
-`frontendMetricsMaxPerMinute` - How many requests per minute per IP is allowed against POST `/api/frontend/metrics` before returning 429. Set to 6000 by default (100rps) - Overridable with `FRONTEND_METRICS_RATE_LIMIT_PER_MINUTE` environment variable
-`frontendRegisterMaxPerMinute` - How many requests per minute per IP is allowed against POST `/api/frontend/register` before returning 429. Set to 6000 by default (100rps) - Overridable with `REGISTER_FRONTEND_RATE_LIMIT_PER_MINUTE` environment variable
- **rateLimiting** - Use the following to tweak the rate limits for `POST /auth/simple` (Password-based login) and `POST /api/admin/user-admin` (Creating users)
-`simpleLoginMaxPerMinute` - How many requests per minute per IP is allowed against POST `/auth/simple` before returning 429. Set to 10 by default - Overridable with `SIMPLE_LOGIN_LIMIT_PER_MINUTE` environment variable
-`createUserMaxPerMinute` - How many requests per minute per IP is allowed against POST `/api/admin/user-admin` before returning 429. Set to 20 by default - Overridable with `CREATE_USER_RATE_LIMIT_PER_MINUTE` environment variable
If you're using Unleash as part of a larger express app, you can disable the automatic server start by calling `server.create`. It takes the same options as `server.start`, but will not begin listening for connections.
console.log(`Unleash app generated and attached to parent application`);
};
start();
```
### Graceful shutdown {#shutdown-unleash}
> PS! Unleash will listen for the `SIGINT` signal and automatically trigger graceful shutdown of Unleash.
If you need to stop Unleash (close database connections, and stop running Unleash tasks) you may use the stop function. Be aware that it is not possible to restart the Unleash instance after stopping it, but you can create a new instance of Unleash.
Changing segment limits could have a negative impact on the performance of Unleash SDKs and cause network congestion. Think twice before changing these values.
Some facets of the [segments feature](/reference/segments.mdx) can be customized via environment variables. This lets you change the [segment limits](/reference/segments.mdx#segment-limits) that Unleash uses.
`UNLEASH_SEGMENT_VALUES_LIMIT` controls the maximum number of values that you can assign across a segment's constraints. The default is 1000 (Since v5.1.0; it was 100 before v5.1.0)
By default, `unleash` uses [log4js](https://github.com/nomiddlename/log4js-node) to log important information. It is possible to swap out the logger provider (only when using Unleash programmatically). You do this by providing an implementation of the **getLogger** function as This enables filtering of log levels and easy redirection of output streams.
```javascript
function getLogger(name) {
// do something with the name
return {
debug: console.log,
info: console.log,
warn: console.log,
error: console.error,
};
}
```
The logger interface with its `debug`, `info`, `warn` and `error` methods expects format string support as seen in `debug` or the JavaScript `console` object. Many commonly used logging implementations cover this API, e.g., bunyan, pino or winston.
In-code configuration values take precedence over environment values: If you provide a database username both via environment variables and in code with the Unleash options object, Unleash will use the in-code username.
The available options are listed in the table below. Options can be specified either via JavaScript (only when starting Unleash via code) or via environment variables. The "property name" column below gives the name of the property on the Unleash options' `db` object.
| `database` | `DATABASE_NAME` | `unleash` | The name of the database. |
| `ssl` | `DATABASE_SSL` | N/A | An object describing SSL options. In code, provide a regular JavaScript object. When using the environment variable, provide a **stringified JSON object**. |
| `pool` | N/A (use the below variables) | | An object describing database pool options. With environment variables, use the options below directly. |
| `pool.min` | `DATABASE_POOL_MIN` | 0 | The minimum number of connections in the connection pool. |
| `pool.max` | `DATABASE_POOL_MAX` | 4 | The maximum number of connections in the connection pool. |
| `pool.idleTimeoutMillis` | `DATABASE_POOL_IDLE_TIMEOUT_MS` | 30000 | The amount of time (in milliseconds) that a connection must be idle for before it is marked as a candidate for eviction. |
| `applicationName` | `DATABASE_APPLICATION_NAME` | `unleash` | The name of the application that created this Client instance. |
| `schema` | `DATABASE_SCHEMA` | `public` | The schema to use in the database. |
Alternatively, you can use a single-host [libpq connection string](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) to connect to the database. You can provide it directly or from a file by using one of the below options. In JavaScript, these are top-level properties of the root configuration object, _not_ the `db` object.
| `databaseUrl` | `DATABASE_URL` | N/A | A string that matches a single-host [libpq connection string](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING), such as `postgres://USER:PASSWORD@HOST:PORT/DATABASE`. Unleash does **not** support using multiple hosts. |
| `databaseUrlFile` | `DATABASE_URL_FILE` | N/A | The path to a file that contains a [libpq connection string](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING). |
When initializing Unleash from code, you'll provide the `db.ssl` option as a JavaScript object. As such, any functions will get evaluated before the object is used for configuration. When using the `DATABASE_SSL` environment variable, you must provide the value as a stringified JSON object. The object will get parsed before being used for configuration, but no further evaluation will take place.
If you want to read content from a file, you should either initialize Unleash via JavaScript or manually interpolate the required values into the environment variable:
To use self-signed certificates, you should set the SSL property `rejectUnauthorized` to `false` and set the `ca` property to the value of the certificate:
Unleash builds directly on the [node-postgres library](https://node-postgres.com/features/ssl), so we support all the same SSL modes that they support. As of version 8 (released on February 25th 2020), [node-postgres no longer supports all sslmodes](https://node-postgres.com/announcements#2020-02-25). For this reason, Unleash cannot support all of Postgres' SSL modes. Specifically, Unleash **does not support**`sslmode=prefer`. Instead you must know whether you require an SSL connection ahead of time.
- Check the default values of connection pool about idle session handling.
- If you have a network component which closes idle sessions on the TCP layer, make sure that the connection pool's `idleTimeoutMillis` setting is lower than the `timespan` setting. If it isn't, then the network component will close the connection.
### Troubleshooting: missing metrics from connected Edge instances
If you're on Unleash 5.9.0 or newer, you might encounter issues with metrics from connected Edge instances. There are two solutions to this, the recommended way and the one that will work for 5.9.0 but probably not for later versions
#### Recommended
- Make sure you're using the latest Edge, at least v17.0.0
- Make sure you have at least one valid client token configured. Either using the `--token` flag on startup, or via connecting an SDK with a valid token
#### Works in 5.9.0
- If you absolutely cannot upgrade your Edge instances to v17.0.0 or newer you can start Unleash with the environmental flag `UNLEASH_EXPERIMENTAL_EDGE_BULK_METRICS` set to `true`
- This will re-enable an endpoint that was disabled in 5.9.0 to allow users that cannot upgrade Edge just now to stay on an old Edge version, but still get client metrics.
You can configure proxy services that intercept all outgoing requests from Unleash. This lets you use the Microsoft Teams or the Webhook integration for external services, even if the internet can only be reached via a proxy on your machine or container (for example if restricted by a firewall or similiar).
Using above code-snippet, every outgoing request from unleash or its integrations will be subsequently routed through set proxy. If the proxy routing needs to be bypassed or stopped, its possible to stop it by using