UNPKG

@nimpl/ab-tests

Version:

A package for conducting A/B tests on a website using middleware

40 lines (39 loc) 2.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createMiddleware = void 0; const server_1 = require("next/server"); const parse_value_1 = require("./lib/utils/parse-value"); const find_test_1 = require("./lib/find-test"); const cookies_1 = require("./lib/data/cookies"); const createMiddleware = ({ tests, cookieLifeTime }) => (request) => { const pathname = request.nextUrl.pathname; const testCookieRow = request.cookies.get(cookies_1.COOKIE_NAME)?.value; const testCookieTmpRow = request.cookies.get(cookies_1.COOKIE_NAME_TMP)?.value; const testCookieBase = testCookieRow || testCookieTmpRow; if (testCookieBase === "0") return server_1.NextResponse.next(); const prevTestCookie = (0, parse_value_1.parseValue)(testCookieBase); const testResult = (0, find_test_1.findTest)(tests, request, prevTestCookie); if (testResult) { const { id, variantIndex, destination, type = "rewrite", status } = testResult; let next; if (type === "rewrite") { next = server_1.NextResponse.rewrite(new URL(destination, request.url), { status: status || 200 }); } else { next = server_1.NextResponse.redirect(new URL(destination, request.url), { status: status || 307 }); } // We save for the session so that files are uploaded for the same variant next.cookies.set(cookies_1.COOKIE_NAME, JSON.stringify({ id, variantIndex })); // If cookieLifeTime is specified - we save it in case of a session change, but if cookies have already been - it means that it is no longer necessary to add it if (cookieLifeTime && !testCookieBase) { next.cookies.set(cookies_1.COOKIE_NAME_TMP, JSON.stringify({ id, variantIndex }), { maxAge: cookieLifeTime }); } return next; } const next = server_1.NextResponse.next(); // Protection from the participation of the script for the page for non-participating users, since the script has the same path as the page itself next.cookies.set(cookies_1.COOKIE_NAME, "0", { path: pathname }); return next; }; exports.createMiddleware = createMiddleware;