2021-12-21 14:50:41 +01:00
---
title: How to use custom activation strategies
---
2023-07-11 11:35:58 +02:00
:::tip
Use custom activation strategies only for cases where [strategy constraints ](https://docs.getunleash.io/reference/strategy-constraints ) don't give you enough control.
The downside of using a custom activation strategy instead of constraints is that you need to distribute the code of your strategy with Unleash client SDK while on the other hand, [strategy constraints ](https://docs.getunleash.io/reference/strategy-constraints ) work without any extra code or maintenance.
:::
2024-05-24 12:28:49 +02:00
This guide takes you through how to use [custom activation strategies ](../reference/custom-activation-strategies.md ) with Unleash. We'll go through how you define a custom strategy in the admin UI, how you add it to a flag, and how you'd implement it in a [client SDK ](../reference/sdks/index.md ).
2021-12-21 15:45:01 +01:00
2024-05-24 12:28:49 +02:00
In this example we want to define an activation strategy offers a scheduled release of a feature flag. This means that we want the feature flag to be activated after a given date and time.
2021-12-21 14:50:41 +01:00
2021-12-21 15:45:01 +01:00
## Step 1: Define your custom strategy {#step-1}
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
1. **Navigate to the strategies view** . Interact with the "Configure" button in the page header and then go to the "Strategies" link in the dropdown menu that appears.
2021-12-21 14:50:41 +01:00
2022-08-09 16:20:28 +02:00
![A visual guide for how to navigate to the strategies page in the Unleash admin UI. It shows the steps described in the preceding paragraph. ](/img/custom-strategy-navigation.png )
2021-12-22 11:36:08 +01:00
refactor: move docs into new structure / fix links for SEO (#2416)
## What
This (admittedly massive) PR updates the "physical" documentation
structure and fixes url inconsistencies and SEO problems reported by
marketing. The main points are:
- remove or move directories : advanced, user_guide, deploy, api
- move the files contained within to the appropriate one of topics,
how-to, tutorials, or reference
- update internal doc links and product links to the content
- create client-side redirects for all the urls that have changed.
A number of the files have been renamed in small ways to better match
their url and to make them easier to find. Additionally, the top-level
api directory has been moved to /reference/api/legacy/unleash (see the
discussion points section for more on this).
## Why
When moving our doc structure to diataxis a while back, we left the
"physical' files lying where they were, because it didn't matter much to
the new structure. However, that did introduce some inconsistencies with
where you place docs and how we organize them.
There's also the discrepancies in whether urls us underscores or hyphens
(which isn't necessarily the same as their file name), which has been
annoying me for a while, but now has also been raised by marketing as an
issue in terms of SEO.
## Discussion points
The old, hand-written API docs have been moved from /api to
/reference/api/legacy/unleash. There _is_ a /reference/api/unleash
directory, but this is being populated by the OpenAPI plugin, and mixing
those could only cause trouble. However, I'm unsure about putting
/legacy/ in the title, because the API isn't legacy, the docs are. Maybe
we could use another path? Like /old-docs/ or something? I'd appreciate
some input on this.
2022-11-22 10:05:30 +01:00
2. **Define your strategy** . Use the "Add new strategy" button to open the strategy creation form. Fill in the form to define your strategy. Refer to [the custom strategy reference documentation ](../reference/custom-activation-strategies.md#definition ) for a full list of options.
2021-12-22 11:36:08 +01:00
2024-05-24 12:28:49 +02:00
![A strategy creation form. It has fields labeled "strategy name" — "TimeStamp" — and "description" — "activate flag after a given timestamp". It also has fields for a parameter named "enableAfter". The parameter is of type "string" and the parameter description is "Expected format: YYYY-MM-DD HH:MM". The parameter is required. ](/img/timestamp_create_strategy.png )
2021-12-21 14:50:41 +01:00
2024-05-24 12:28:49 +02:00
## Step 2: Apply your custom strategy to a feature flag {#step-2}
2021-12-21 14:50:41 +01:00
2024-05-24 12:28:49 +02:00
**Navigate to your feature flag** and **apply the strategy** you just created.
2021-12-22 11:36:08 +01:00
![The strategy configuration screen for the custom "TimeStamp" strategy from the previous step. The "enableAfter" field says "2021-12-25 00:00". ](/img/timestamp_use_strategy.png )
## Step 3: Implement the strategy in your client SDK {#step-3}
The steps to implement a custom strategy for your client depend on the kind of client SDK you're using:
2022-08-09 16:20:28 +02:00
- if you're using a server-side client SDK, follow the steps in [option A ](#step-3-a 'Step 3 option A: implement the strategy for a server-side client SDK' ).
2023-01-25 14:36:50 +01:00
- if you're using a front-end client SDK ([Android](/docs/generated/sdks/client-side/android-proxy.md), [JavaScript ](/docs/generated/sdks/client-side/javascript-browser.md ), [React ](/docs/generated/sdks/client-side/react.md ), [iOS ](/docs/generated/sdks/client-side/ios-proxy.md )), follow the steps in [option B ](#step-3-b 'Step 3 option B: implementing the strategy for a front-end client SDK' )
2021-12-22 11:36:08 +01:00
2021-12-22 12:37:40 +01:00
### Option A: Implement the strategy for a server-side client SDK {#step-3-a}
2021-12-22 11:36:08 +01:00
docs: auto-generate remaining server-side SDK docs (#2858)
This PR builds on the preceding doc auto-generation PRs and generates
documentation for the remaining server-side SDKs.
## Why
Refer to https://github.com/Unleash/unleash/pull/2809 for more context
about generating SDK docs.
## What
- Adds generation for the remaining server-side SDKs
- Moves generated docs from the `/reference/sdks` directory to
`/generated` directory.
- Makes sure that the URLs do not change because of the move by using
the `slug` frontmatter property.
- replaces relative github links in the markdown documents so that they
become absolute github links. (refer to the next section)
- Updates some image styling so that it doesn't apply to readme badges
(we don't need them using `display: block`)
### On link replacing:
This PR adds handling of links in the generated documentation.
Specifically, it changes links in one case:
Relative links to github. Links to code and other files in the
repository. These are prefixed with the repository's URL.
While this should work in most cases, it will fail in cases where the
links to the files are not on the repository's primary branch.
(typically main, but could also be "v3", for instance). In these cases,
the links will get a double branch in the URL and will fail. However, I
see no easy way around this (though suggestions are definitely
accepted!), and think it's a fair tradeoff. It takes the links from
"definitely failing" to "will work in the vast majority of cases".
Note: I originally also wanted to handle the case where the link is an
absolute link to docs.getunleash.io. We could turn these into relative
urls to avoid full page reloads and enjoy a smoother experience.
However, the client-side redirects don't work correctly if the relative
URL goes to a redirect page, so you end up with a 404 page. As such, I
think it's better to leave the links as absolute for now.
2023-01-13 12:40:28 +01:00
1. **Implement the custom strategy** in your [client SDK ](../reference/sdks/index.md ). The exact way to do this will vary depending on the specific SDK you're using, so refer to the SDK's documentation. The example below shows an example of how you'd implement a custom strategy called "TimeStamp" for the [Node.js client SDK ](/docs/generated/sdks/server-side/node.md ).
2021-12-22 11:36:08 +01:00
```js
const { Strategy } = require('unleash-client');
class TimeStampStrategy extends Strategy {
constructor() {
super('TimeStamp');
}
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
isEnabled(parameters, context) {
2022-01-03 13:08:25 +01:00
return Date.parse(parameters.enableAfter) < Date.now ( ) ;
2021-12-22 11:36:08 +01:00
}
}
```
2021-12-21 14:50:41 +01:00
2022-08-09 16:20:28 +02:00
2. **Register the custom strategy with the Unleash Client** . When instantiating the Unleash Client, provide it with a list of the custom strategies you'd like to use — again: refer to _your_ client SDK's docs for the specifics.
2021-12-21 14:50:41 +01:00
2021-12-22 12:37:40 +01:00
Here's a full, working example for Node.js. Notice the `strategies` property being passed to the `initialize` function.
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
```js
const { Strategy, initialize, isEnabled } = require('unleash-client');
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
class TimeStampStrategy extends Strategy {
constructor() {
super('TimeStamp');
}
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
isEnabled(parameters, context) {
2022-01-03 13:08:25 +01:00
return Date.parse(parameters.enableAfter) < Date.now ( ) ;
2021-12-22 11:36:08 +01:00
}
}
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
const instance = initialize({
2022-10-19 14:02:00 +02:00
url: 'https://unleash.example.com/api/',
2021-12-22 11:36:08 +01:00
appName: 'unleash-demo',
instanceId: '1',
2021-12-22 12:37:40 +01:00
// highlight-next-line
2021-12-22 11:36:08 +01:00
strategies: [new TimeStampStrategy()],
});
2021-12-21 14:50:41 +01:00
2021-12-22 11:36:08 +01:00
instance.on('ready', () => {
setInterval(() => {
console.log(isEnabled('demo.TimeStampRollout'));
}, 1000);
});
```
2021-12-21 14:50:41 +01:00
2021-12-22 12:37:40 +01:00
### Option B: Implement the strategy for a front-end client SDK {#step-3-b}
2021-12-21 14:50:41 +01:00
Source proxy and Edge docs from GitHub (#3122)
## What
The main purpose of this PR is to
1. Delete the proxy docs in this repo and replace them with the proxy's
GitHub readme.
2. Add the docs for Unleash Edge.
### Detailed change description
This PR contains a lot of small changes in a large number of files. To
make it easier to get an overview, here's a detailed description of what
happens where:
#### In the `website/docs`directory
Except for the deletion of the proxy doc, all changes in this directory
are rewriting internal links, so that they point to the newly generated
document instead.
#### `package.json` and `yarn.lock`
When including the documentation for Edge, we also want to render the
mermaid diagrams it uses. Docusaurus supports this via a plugin. All
changes in these files are related to installing that plugin.
#### `docusaurus.config.js`
There's two types of changes in this file:
1. Mermaid-related changes: we ask docusaurus to render mermaid in
markdown files and add the plugin
2. Document generation. There's some rewrites to the sdk doc generation
plus an entirely new section that generates docs for Edge and the proxy
#### `sidebars.js`
Two things:
1. Add the edge docs
2. Move both the Edge and the proxy docs up a level, so that they're
directly under "reference docs" instead of nested inside "unleash
concepts".
#### In the `website/remote-content` directory
These are the remote content files. Previously, all of this lived only
in a `readme-fns.js` file, but with the introduction of Edge and proxy
docs, this has been moved into its own directory and refactored into
three files (`shared`, `sdks`, `edge-proxy`).
#### `custom.css`
Style updates to center mermaid diagrams and provide more space around
them.
#### In `static/img`
The image files that were included in the proxy doc and that have been
deleted.
## Why
For two reasons:
1. Reduce duplication for the proxy. Have one source of truth.
2. Add docs for edge.
## Discussion points and review wishes
This is a big PR, and I don't expect anyone to do a line-by-line review
of it, nor do I think that is particularly useful. Instead, I'd like to
ask reviewers to:
1. Visit the [documentation
preview](https://unleash-docs-git-docs-source-proxy-gh-unleash-team.vercel.app/reference/unleash-proxy)
and have a look at both the proxy docs and the Edge docs. Potentially
have a look at the SDK docs too to verify that everything still works.
2. Consider whether they think moving the proxy and edge docs up a level
(in the sidebar) makes sense.
3. Let me know what slug they'd prefer for the Edge docs. I've gone with
`unleash-edge` for now (so that it's
`docs.getunleash.io/reference/unleash-edge`), but we could potentially
also just use `edge`. WDYT?
4. Read through the detailed changes section.
5. Let me know if they have any other concerns or questions.
## Screenies
The new proxy doc:
![image](https://user-images.githubusercontent.com/17786332/219043145-1c75c83e-4191-45a3-acb5-775d05d13862.png)
The new edge doc:
![image](https://user-images.githubusercontent.com/17786332/219043220-1f5daf13-972e-4d56-8aaf-70ff1812863e.png)
2023-02-16 13:36:28 +01:00
Front-end client SDKs don't evaluate strategies directly, so you need to implement the **custom strategy in the [Unleash Proxy](../generated/unleash-proxy.md)** . Depending on how you run the Unleash Proxy, follow one of the below series of steps:
2022-08-09 16:20:28 +02:00
2022-01-03 10:12:13 +01:00
- If you're running the Unleash Proxy as a Docker container, refer to the [steps for using a containerized Proxy ](#step-3-b-docker ).
- If you're using the Unleash Proxy via Node.js, refer to the [steps for using custom strategies via Node.js ](#step-3-b-node ).
#### With a containerized proxy {#step-3-b-docker}
2021-12-21 14:50:41 +01:00
Source proxy and Edge docs from GitHub (#3122)
## What
The main purpose of this PR is to
1. Delete the proxy docs in this repo and replace them with the proxy's
GitHub readme.
2. Add the docs for Unleash Edge.
### Detailed change description
This PR contains a lot of small changes in a large number of files. To
make it easier to get an overview, here's a detailed description of what
happens where:
#### In the `website/docs`directory
Except for the deletion of the proxy doc, all changes in this directory
are rewriting internal links, so that they point to the newly generated
document instead.
#### `package.json` and `yarn.lock`
When including the documentation for Edge, we also want to render the
mermaid diagrams it uses. Docusaurus supports this via a plugin. All
changes in these files are related to installing that plugin.
#### `docusaurus.config.js`
There's two types of changes in this file:
1. Mermaid-related changes: we ask docusaurus to render mermaid in
markdown files and add the plugin
2. Document generation. There's some rewrites to the sdk doc generation
plus an entirely new section that generates docs for Edge and the proxy
#### `sidebars.js`
Two things:
1. Add the edge docs
2. Move both the Edge and the proxy docs up a level, so that they're
directly under "reference docs" instead of nested inside "unleash
concepts".
#### In the `website/remote-content` directory
These are the remote content files. Previously, all of this lived only
in a `readme-fns.js` file, but with the introduction of Edge and proxy
docs, this has been moved into its own directory and refactored into
three files (`shared`, `sdks`, `edge-proxy`).
#### `custom.css`
Style updates to center mermaid diagrams and provide more space around
them.
#### In `static/img`
The image files that were included in the proxy doc and that have been
deleted.
## Why
For two reasons:
1. Reduce duplication for the proxy. Have one source of truth.
2. Add docs for edge.
## Discussion points and review wishes
This is a big PR, and I don't expect anyone to do a line-by-line review
of it, nor do I think that is particularly useful. Instead, I'd like to
ask reviewers to:
1. Visit the [documentation
preview](https://unleash-docs-git-docs-source-proxy-gh-unleash-team.vercel.app/reference/unleash-proxy)
and have a look at both the proxy docs and the Edge docs. Potentially
have a look at the SDK docs too to verify that everything still works.
2. Consider whether they think moving the proxy and edge docs up a level
(in the sidebar) makes sense.
3. Let me know what slug they'd prefer for the Edge docs. I've gone with
`unleash-edge` for now (so that it's
`docs.getunleash.io/reference/unleash-edge`), but we could potentially
also just use `edge`. WDYT?
4. Read through the detailed changes section.
5. Let me know if they have any other concerns or questions.
## Screenies
The new proxy doc:
![image](https://user-images.githubusercontent.com/17786332/219043145-1c75c83e-4191-45a3-acb5-775d05d13862.png)
The new edge doc:
![image](https://user-images.githubusercontent.com/17786332/219043220-1f5daf13-972e-4d56-8aaf-70ff1812863e.png)
2023-02-16 13:36:28 +01:00
Strategies are stored in separate JavaScript files and loaded into the container at startup. Refer to [the Unleash Proxy documentation ](../generated/unleash-proxy.md ) for a full overview of all the options.
2021-12-21 14:50:41 +01:00
2021-12-22 12:37:40 +01:00
1. **Create a strategies directory.** Create a directory that Docker has access to where you can store your strategies. The next steps assume you called it `strategies`
2022-01-04 10:19:32 +01:00
2. **Initialize a Node.js project** and **install the Unleash Client** :
2021-12-21 14:50:41 +01:00
2022-08-09 16:20:28 +02:00
```shell npm2yarn
2021-12-22 12:37:40 +01:00
npm init -y & & \
npm install unleash-client
```
2022-08-09 16:20:28 +02:00
3. **Create a strategy file** and **implement your strategies** . Remember to **export your list of strategies** . The next steps will assume you called the file `timestamp.js` . An example implementation looks like this:
2021-12-22 12:37:40 +01:00
2022-08-09 16:20:28 +02:00
```js
2021-12-22 12:37:40 +01:00
const { Strategy } = require('unleash-client');
class TimeStampStrategy extends Strategy {
constructor() {
super('TimeStamp');
}
isEnabled(parameters, context) {
2022-01-03 13:08:25 +01:00
return Date.parse(parameters.enableAfter) < Date.now ( ) ;
2021-12-22 12:37:40 +01:00
}
}
module.exports = [new TimeStampStrategy()]; // < - export strategies
```
4. **Mount the strategies directory** and **point the [Unleash Proxy docker container](https://hub.docker.com/r/unleashorg/unleash-proxy) at your strategies file** . The highlighted lines below show the extra options you need to add. The following command assumes that your strategies directory is a direct subdirectory of your current working directory. Modify the rest of the command to suit your needs.
2022-08-09 16:20:28 +02:00
```shell
2021-12-22 12:37:40 +01:00
docker run --name unleash-proxy --pull=always \
2022-08-09 16:20:28 +02:00
-e UNLEASH_PROXY_CLIENT_KEYS=some-secret \
2021-12-22 14:20:07 +01:00
-e UNLEASH_URL='http://unleash:4242/api/' \
-e UNLEASH_API_TOKEN=${API_TOKEN} \
2021-12-22 14:21:04 +01:00
# highlight-start
2021-12-22 14:20:07 +01:00
-e UNLEASH_CUSTOM_STRATEGIES_FILE=/strategies/timestamp.js \
--mount type=bind,source="$(pwd)"/strategies,target=/strategies \
2021-12-22 14:21:04 +01:00
# highlight-end
2021-12-22 14:20:07 +01:00
-p 3000:3000 --network unleash unleashorg/unleash-proxy
2021-12-22 12:37:40 +01:00
```
2022-01-03 10:12:13 +01:00
2022-01-04 10:19:32 +01:00
#### When running the proxy with Node.js {#step-3-b-node}
2022-01-03 10:12:13 +01:00
The Unleash Proxy accepts a `customStrategies` property as part of its initialization options. Use this to pass it initialized strategies.
1. **Install the `unleash-client` package** . You'll need this to implement the custom strategy:
2022-08-09 16:20:28 +02:00
```shell npm2yarn
2022-01-03 10:12:13 +01:00
npm install unleash-client
```
2. **Implement your strategy** . You can import it from a different file or put it in the same file as the Proxy initialization. For instance, a `TimeStampStrategy` could look like this:
2022-08-09 16:20:28 +02:00
```js
2022-01-03 10:12:13 +01:00
const { Strategy } = require('unleash-client');
class TimeStampStrategy extends Strategy {
constructor() {
super('TimeStamp');
}
isEnabled(parameters, context) {
2022-01-03 13:08:25 +01:00
return Date.parse(parameters.enableAfter) < Date.now ( ) ;
2022-01-03 10:12:13 +01:00
}
}
```
3. **Pass the strategy to the Proxy Client** using the ** `customStrategies` ** option. A full code example:
2022-08-09 16:20:28 +02:00
```javascript
2022-01-03 10:19:04 +01:00
const { createApp } = require('@unleash/proxy');
const { Strategy } = require('unleash-client');
class TimeStampStrategy extends Strategy {
constructor() {
super('TimeStamp');
}
isEnabled(parameters, context) {
2022-01-03 13:08:25 +01:00
return Date.parse(parameters.enableAfter) < Date.now ( ) ;
2022-01-03 10:19:04 +01:00
}
}
const port = 3000;
const app = createApp({
2022-08-09 16:20:28 +02:00
unleashUrl: 'https://app.unleash-hosted.com/demo/api/',
unleashApiToken:
'*:default.56907a2fa53c1d16101d509a10b78e36190b0f918d9f122d',
clientKeys: ['proxy-secret', 'another-proxy-secret', 's1'],
refreshInterval: 1000,
// highlight-next-line
customStrategies: [new TimeStampStrategy()],
2022-01-03 10:19:04 +01:00
});
app.listen(port, () =>
2022-08-09 16:20:28 +02:00
// eslint-disable-next-line no-console
console.log(`Unleash Proxy listening on http://localhost:${port}/proxy`),
2022-01-03 10:19:04 +01:00
);
```