How to write pre-request script when use K6 to test the API?

Background: When I use K6 to test the API, I need to encrypt the parameters of the API with MD5 before sending it to the server. How to write this pre-request script? Who can provide a K6 js demo ?

hey! This k6 document will help! Let me know how it goes.

This document only describes how to use the MD5 function, but I would like to know how to write a pre-request script with k6 before sending requests to the API server. Can you provide an example? Thanks a lot!

Hi, you can combine all these examples like this:

import crypto from 'k6/crypto';
import http from 'k6/http';

export default function () {
  let hash = crypto.md5('hello world!', 'hex');
  const binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
  hash = crypto.md5(new Uint8Array(binArray).buffer, 'hex');

  // header for first request
  const params = {
      headers: {
          'Content-Type': 'application/json',
          'SECRET_MD5': hash

  // open main page
  let res = http.get('', params);
  // check response
  check(res, {
      'is status 200': (r) => r.status === 200