(Optional) Add authentication to your spike script
Note
This milestone is optional. The QuickPizza home page doesn’t require a token, but its API routes (such as /api/pizza) require a demo token, such as
Token abcdef0123456789, and return401without it. For realistic practice with your own credentials, point the URLs and environment variables at your own staging API that expects a bearer token or API key, so a missing or invalid token makes yourcheck()assertions fail loudly.
Spike tests are only realistic when they hit the same code paths as production. Protected routes often add token validation, caching, and rate limits that an unauthenticated script never exercises. The standard k6 pattern is to read secrets from the environment, never hard-code them in the script.
To add authentication to your spike requests, complete the following steps:
Choose an environment variable name for the credential, for example
SPIKE_API_TOKEN. Do not commit real tokens to Git; set the variable only in your shell session, CI secret store, or Grafana Cloud k6 test secrets when you run for real.At the top of your script (below imports), read the token once. Keep your existing
export const optionsblock unchanged immediately after:import http from 'k6/http'; import { check, sleep } from 'k6'; const token = __ENV.SPIKE_API_TOKEN || ''; export const options = { stages: [ /* … your existing stages … */ ], thresholds: { /* … your existing thresholds … */ }, };Copy your real
stagesandthresholdsfromspike.jsorspike-multi.jsin place of the comments.Add a small helper so every request can attach the same headers when a token is present:
function authHeaders() { if (!token) { return {}; } return { headers: { Authorization: `Bearer ${token}`, }, }; }Merge those headers into each request. For a GET with URL grouping and tags:
const res = http.get(http.url`https://your-api.example.com/api/status`, { ...authHeaders(), tags: { name: 'GET_status' }, });For POST requests, merge
authHeaders().headersinto your existingheadersobject (for example keepContent-Type: application/jsonand addAuthorizationin the same object).Run the script with the variable set for one local check:
SPIKE_API_TOKEN=your-staging-token k6 run spike.jsConfirm that status checks match what your API returns for valid credentials (
200/204) versus missing or invalid tokens (401/403).
Open Turn spike results into action in the sidebar to plan follow-up work.
At this point in your path, you can explore the following topics: