Hono
Server SDK on Hono with manual cookie handling
This example runs a server side A/B test on a Hono server using the ImproveServerSDK directly. Unlike the Next.js example — where the middleware handles cookies for you — here you manage the visitor and test cookies yourself, which makes it a good reference for any server framework that is not Next.js.
Install
npm i @obelism/improve-sdk honoHandler
The flow on each request is:
fetchConfigto load the datafile.- Read the visitor id and test value from cookies, using
getVisitorCookieNamefor the cookie name. - Validate those cookie values with
validateVisitorIdandvalidateTestValue; fall back togenerateVisitorIdandgetTestValuewhen they are missing or invalid. - Re-store both values in cookies so the visitor keeps the same variant on future visits.
import { ImproveServerSDK } from '@obelism/improve-sdk/server'
import { Hono } from 'hono'
import { getCookie, setCookie } from 'hono/cookie'
const app = new Hono()
const improveSdk = new ImproveServerSDK({
organizationId: 'org_MJFL46Z0WXGQ5OHW1ZXSM3Q88S',
environment: 'staging',
token: 'xxxx-xxxx-xxxx-xxxx',
})
const AB_TEST_SLUG = 'startpage-visual'
app.get('/', async (c) => {
//? Get config from Improve
await improveSdk.fetchConfig()
//? Get values from cookie for a consistent browsing experience for users
const visitorCookieName = improveSdk.getVisitorCookieName()
const visitorIdCookie = getCookie(c, visitorCookieName)
const testCookieValue = getCookie(c, AB_TEST_SLUG)
//? Validate if the cookie values are valid
const validCookieVisitorId =
visitorIdCookie && improveSdk.validateVisitorId(visitorIdCookie)
const validCookieValue =
testCookieValue &&
improveSdk.validateTestValue(AB_TEST_SLUG, testCookieValue)
const visitorId = validCookieVisitorId
? visitorIdCookie
: improveSdk.generateVisitorId()
const testValue = validCookieValue
? testCookieValue
: improveSdk.getTestValue(
AB_TEST_SLUG,
visitorId,
c.req.header('User-Agent') || '',
)
//? Re-store values in cookies for one week
setCookie(c, visitorCookieName, visitorId, {
maxAge: 60 * 60 * 24 * 7,
})
setCookie(c, AB_TEST_SLUG, testValue, {
maxAge: 60 * 60 * 24 * 7,
})
return c.text(`AB Test: ${testValue}`)
})
export default appNote: the runnable example hardcodes the server token for brevity. In your own app load it from an environment variable so it never ends up in version control.