Creating customized user experiences using Express JS and LaunchDarkly segment targeting featured image

Treating every user the same is risky when they may have different goals, dreams, desires, and features they care about. To provide the best experience, you want to customize your website based on what you know about your users. Luckily, LaunchDarkly makes it easy to do just that. 

In this tutorial, you will learn how to use segment targeting to show users with a .edu email address a student version of your website using LaunchDarkly and Express JS. 


Express is the most popular, mature, stable Node.js server framework. As of publication, it has over 65k stars on GitHub, 33 million weekly downloads, and is hosted by the OpenJS Foundation.

Prerequisites

First, clone this repository on your local machine:

git clone https://github.com/annthurium/express-launchdarkly-starter 

If you want to cut to the chase, a code-complete demo repo lives here.

Once cloned, navigate into your project directory:

cd express-launchdarkly-starter

Next, configure your credentials.

Go to https://app.launchdarkly.com/settings/projects. Click on the project you want to work in. Copy the SDK key from the Environments tab on the following screen:

Screenshot demonstrating how to copy your SDK key from the LaunchDarkly application.

Important—SDK keys are environment-specific, so use the key from your “Production” environment. Paste the key into the .env.example file. Rename the .env.example file to .env.

With this setup, the LaunchDarkly SDK can access the credentials locally, but you won’t accidentally commit them to source control and compromise your security.

Install dependencies using the following command:

npm install

Run the server:

npm start

Load http://127.0.0.1:3000/  in the browser. You should see a “hello, world” page.


There are also a few static html templates in this repo. If you go to http://127.0.0.1:3000/enterprise.html you should see an enterprise version of the website. http://127.0.0.1:3000/student.html will take you to a student version with more festive colors.

What are segments?

Segments are groups that allow you to consistently target the same audiences, serving as a single source of truth for your targeting logic. While nothing stops you from duplicating targeting rules across different flags, keeping everything up to date when requirements change can be a major time sink. That’s where segments come in.

Segments can be shared across LaunchDarkly environments, making it easier to keep things in sync between dev/test and production. Let’s create a segment, add a targeting rule, and then use it in a flag.

Head back to the LaunchDarkly application. Ensure you’re in the Production environment matching the SDK key you copied into your .env file. 

Click “Segments” on the left-hand menu, and then click one of the “Create segment” buttons.

Screenshot of LaunchDarkly UI for creating a segment.

Select “Rule-based segments” in the next section.

Select "Rule-based segments" from this dialog.

In the following window, choose a name for your segment. Enter a description as a gift for your future self. Click “Save segment”.

Enter segment name and description.

On the following screen, create a rule. Select the following values and save. 

  • Context kind: user
  • Attribute: email
  • Operator: ends with
  • Values: .edu

Create a segment rule.

You’ll be prompted to enter a comment explaining your changes and confirm them.

Dialog box requiring confirmation before rule is added in Production.

Finally, you’ll create a flag that targets that specific segment. Hang in there, we’re almost through configuring things. 

On the left navigation menu, click “Flags” and then the “Create Flag” button.

Empty state for flag creation flow. You can click either of the "Create flag" buttons.

Name this flag “show-student-version”, matching the flagKey variable in your application code. The key will auto-populate. The flag type is Boolean, and you can leave the “variations” input boxes blank. Click the “Create flag” button when you’re done typing in the name and description.

Describe a flag's purpose and create a key to refer to it later in your code.

On the next screen, click the “add rule” dropdown and select “Target segments.” Configure the rule as follows, and then click “Confirm and save.” 

  • If Context is in Students, serve true
  • When no targeting rules are matched (the "Default rule"), serve false
  • Flag is On

UI for adding a rule to a flag in a Production environment.

In the “Save” dialog, add a comment explaining these changes. Type “production” to confirm the environment.

Dialog box confirming changes to a production flag.

How to use a LaunchDarkly flag in your Express application

To initialize the LaunchDarkly client, you need the SDK key which is in your .env file. Back in the index.js file, add some code to grab the value of that variable and initialize the client. Add the following commented lines of code to index.js:

const express = require("express");
const path = require("path");
const serveStatic = require("serve-static");


// add these new dependencies
const ld = require("@launchdarkly/node-server-sdk");
require("dotenv").config();

const app = express();

app.use(serveStatic(path.join(__dirname, "public")));

// add the following lines of code to initialize the LaunchDarkly client
const sdkKey = process.env.LAUNCHDARKLY_SDK_KEY;
const ldClient = ld.init(sdkKey);

// replace the entire app.get function with this version
app.get("/", async function (req, res) {
 const context = {
   kind: "user",
   key: "user-key-123abcde",
   email: "biz@face.dev",
 };
 const showStudentVersion = await ldClient.variation(
   "show-student-version",
   context,
   false
 );
 let fileName;
 if (showStudentVersion) {
   fileName = "student.html";
 } else {
   fileName = "enterprise.html";
 }
 res.redirect(fileName);
});

const port = 3000;
const server = app.listen(port, function (err) {
 if (err) console.log("Error in server setup");
 console.log(`Server listening on http://localhost:${port}`);
});

// Add this new function to gracefully close the connection to the LaunchDarkly server.
process.on("SIGTERM", () => {
 debug("SIGTERM signal received: closing HTTP server");
 ld.close();
 server.close(() => {
   debug("HTTP server closed");
   ldClient.close();
 });
});

In the context variable, we are passing information about our user to LaunchDarkly, including the email address. The show-student–version flag is set to ‘On’, but the user’s email address doesn’t match our targeting rule for students. Go to http://127.0.0.1:3000, you should be redirected to the enterprise version of the website. 


Try changing the email address in the context to something that ends in .edu. Save these changes in your editor:

 const context = {
   kind: "user",
   key: "user-key-123abcde",
   email: "learner@student.edu",
 };

Go back to http://127.0.0.1:3000. Without changing any of your flag configurations or targeting in LaunchDarkly, the app should have redirected you to the student version of the website. Tada! 🏁

If it’s not working - here’s some steps to double check:

  • double-check that your flag is set to “On” and you’ve targeted your user segment.
  • Check your route is http://127.0.0.1:300  —  you were redirected to enterprise.html after you loaded the page for the first time. 
  • Make sure you’ve clicked “confirm and Save” after turning your flag on.
  • Make sure your .env.example file has been renamed to .env.

The flag interface, with a red arrow next to the switch toggling the flag On.

Conclusion: adding conditional routing in an Express application to customize your user experience

In this tutorial, you’ve learned how to use LaunchDarkly to target different segments of your audience. By using targeting rules and segments, you can create custom user experiences, avoid duplicating flag rules, and showcase different features of your site based on a user’s email address.

Email addresses are just the beginning. You can target just about any user attribute: name, plan type, zip code, and more.  Read more about how to target users based on context attributes in the LaunchDarkly docs.

If you’re curious about other was you can use LaunchDarkly to improve software delivery, you might enjoy:

Thanks so much for reading! If you have any questions, or just want to synergize your enterprise applications in my general direction, you can circle back via email (tthurium@launchdarkly.com), X/Twitter, or LinkedIn

Like what you read?
Get a demo
Related Content

More about Feature Flags

September 20, 2024