> ## Documentation Index
> Fetch the complete documentation index at: https://moeck.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Response Actions

> Define what MockServer returns when an expectation matches: a response, a forward, a callback, or an error.

When a request matches an [expectation](/mocking/expectations), MockServer executes the expectation's **action**. There are four action types:

<CardGroup cols={2}>
  <Card title="Response" icon="reply">Return a fixed or templated HTTP response.</Card>
  <Card title="Forward" icon="arrow-right">Proxy the request to another server, optionally modifying it.</Card>
  <Card title="Callback" icon="code">Invoke a Java class or closure to generate the response dynamically.</Card>
  <Card title="Error" icon="triangle-exclamation">Return invalid bytes or drop the connection to simulate network failures.</Card>
</CardGroup>

## Response

A **response** action returns an HTTP response you define. You can set the status code, reason phrase, headers, cookies, body, and delay.

### Status code and reason phrase

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(
          request()
              .withMethod("POST")
              .withPath("/some/path")
      )
      .respond(
          response()
              .withStatusCode(418)
              .withReasonPhrase("I'm a teapot")
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": {
          "method": "POST",
          "path": "/some/path"
      },
      "httpResponse": {
          "statusCode": 418,
          "reasonPhrase": "I'\''m a teapot"
      }
  }'
  ```
</CodeGroup>

### Headers, cookies, and body

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(request())
      .respond(
          response()
              .withBody("some_response_body")
              .withHeader("Content-Type", "plain/text")
              .withCookie("Session", "97d43b1e-fe03-4855-926a-f448eddac32f")
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT http://localhost:1080/mockserver/expectation -d '{
      "httpResponse": {
          "headers": {
              "Content-Type": ["plain/text"]
          },
          "cookies": {
              "Session": "97d43b1e-fe03-4855-926a-f448eddac32f"
          },
          "body": "some_response_body"
      }
  }'
  ```
</CodeGroup>

### Delay

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(
          request().withPath("/some/path")
      )
      .respond(
          response()
              .withBody("some_response_body")
              .withDelay(TimeUnit.SECONDS, 10)
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some/path" },
      "httpResponse": {
          "body": "some_response_body",
          "delay": {
              "timeUnit": "SECONDS",
              "value": 10
          }
      }
  }'
  ```
</CodeGroup>

### Connection options

Use `connectionOptions` to suppress or override automatically-added headers, or to close the socket:

<CodeGroup>
  ```java Java theme={null}
  response()
      .withBody("some_response_body")
      .withConnectionOptions(
          connectionOptions()
              .withSuppressConnectionHeader(true)
              .withSuppressContentLengthHeader(true)
      )
  ```

  ```json REST API theme={null}
  "httpResponse": {
      "body": "some_response_body",
      "connectionOptions": {
          "suppressContentLengthHeader": true,
          "suppressConnectionHeader": true
      }
  }
  ```
</CodeGroup>

Close the connection after sending the response:

```json theme={null}
"connectionOptions": { "closeSocket": true }
```

Close the connection after a delay:

```json theme={null}
"connectionOptions": {
    "closeSocket": true,
    "closeSocketDelay": { "timeUnit": "MILLISECONDS", "value": 500 }
}
```

### Respond differently for the same request

Register multiple expectations with the same matcher and different `times` values. MockServer fires them in registration order:

```bash theme={null}
# respond once with 200, then twice with 204
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": { "path": "/some/path" },
    "httpResponse": { "statusCode": 200 },
    "times": { "remainingTimes": 1, "unlimited": false }
}'

curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": { "path": "/some/path" },
    "httpResponse": { "statusCode": 204 },
    "times": { "remainingTimes": 2, "unlimited": false }
}'
```

### Response templates

You can use Mustache, Velocity, or JavaScript templates to generate responses dynamically from the incoming request. See [Response Templates](/mocking/response-templates).

<CodeGroup>
  ```java Java (JavaScript template) theme={null}
  new MockServerClient("localhost", 1080)
      .when(request().withPath("/some/path"))
      .respond(
          template(
              HttpTemplate.TemplateType.JAVASCRIPT,
              "return {\n" +
              "    'statusCode': 200,\n" +
              "    'cookies': { 'session': request.headers['Session-Id'][0] },\n" +
              "    'headers': { 'Date': [ Date() ] },\n" +
              "    'body': JSON.stringify({ method: request.method, path: request.path })\n" +
              "};"
          )
      );
  ```

  ```bash REST API (JavaScript template) theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some/path" },
      "httpResponseTemplate": {
          "template": "return { statusCode: 200, cookies: { session: request.headers[\"Session-Id\"] && request.headers[\"Session-Id\"][0] }, headers: { Date: [ Date() ] }, body: JSON.stringify({method: request.method, path: request.path}) };",
          "templateType": "JAVASCRIPT"
      }
  }'
  ```
</CodeGroup>

## Forward

A **forward** action proxies the incoming request to another server.

### Forward exact request

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(
          request().withPath("/some/path")
      )
      .forward(
          forward()
              .withHost("mock-server.com")
              .withPort(80)
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some/path" },
      "httpForward": {
          "host": "mock-server.com",
          "port": 80,
          "scheme": "HTTP"
      }
  }'
  ```
</CodeGroup>

Use `"scheme": "HTTPS"` to forward over TLS:

```json theme={null}
"httpForward": {
    "host": "mock-server.com",
    "port": 443,
    "scheme": "HTTPS"
}
```

### Override the forwarded request

Replace specific fields of the request before forwarding:

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(
          request().withPath("/some/path")
      )
      .forward(
          forwardOverriddenRequest(
              request()
                  .withPath("/some/other/path")
                  .withHeader("Host", "target.host.com")
          )
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some/path" },
      "httpOverrideForwardedRequest": {
          "httpRequest": {
              "path": "/some/other/path",
              "headers": { "Host": ["target.host.com"] }
          }
      }
  }'
  ```
</CodeGroup>

### Override both request and response

You can override the forwarded request and also replace the response body returned to the caller:

```json theme={null}
"httpOverrideForwardedRequest": {
    "httpRequest": {
        "path": "/some/other/path",
        "headers": { "Host": ["target.host.com"] }
    },
    "httpResponse": {
        "body": "some_overridden_body"
    }
}
```

### Add delay to a forward

```json theme={null}
"httpOverrideForwardedRequest": {
    "httpRequest": { "path": "/some/other/path" },
    "delay": { "timeUnit": "SECONDS", "value": 10 }
}
```

## Callback

A **callback** action dynamically generates the response (or the forwarded request) by invoking code you provide. There are two variants: a **class callback** (server-side, Java only) and a **method/closure callback** (client-side, via WebSocket).

### Class callback

Implement `ExpectationResponseCallback` and register it by class name. The class must be on MockServer's classpath and have a zero-argument constructor.

<CodeGroup>
  ```java Java theme={null}
  public class TestExpectationResponseCallback implements ExpectationResponseCallback {

      @Override
      public HttpResponse handle(HttpRequest httpRequest) {
          if (httpRequest.getPath().getValue().endsWith("/path")) {
              return response()
                  .withStatusCode(202)
                  .withBody("a_callback_response");
          } else {
              return notFoundResponse();
          }
      }
  }

  new ClientAndServer(1080)
      .when(
          request().withPath("/some.*")
      )
      .respond(
          callback()
              .withCallbackClass(TestExpectationResponseCallback.class)
      );
  ```

  ```javascript JavaScript theme={null}
  var mockServerClient = require('mockserver-client').mockServerClient;
  mockServerClient("localhost", 1080).mockAnyResponse({
      "httpRequest": { "path": "/some.*" },
      "httpResponseClassCallback": {
          "callbackClass": "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationResponseCallback"
      }
  });
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some.*" },
      "httpResponseClassCallback": {
          "callbackClass": "org.mockserver.examples.mockserver.CallbackActionExamples$TestExpectationResponseCallback"
      }
  }'
  ```
</CodeGroup>

<Note>
  When using the Maven plugin with forked goals, add callback classes as plugin `dependencies` so MockServer can load them from the classpath.
</Note>

## Error

An **error** action simulates network-level failures by sending invalid bytes or dropping the TCP connection.

### Drop the connection

<CodeGroup>
  ```java Java theme={null}
  new MockServerClient("localhost", 1080)
      .when(
          request().withPath("/some/path")
      )
      .error(
          error()
              .withDropConnection(true)
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some/path" },
      "httpError": { "dropConnection": true }
  }'
  ```
</CodeGroup>

### Send random bytes then drop

<CodeGroup>
  ```java Java theme={null}
  byte[] randomByteArray = new byte[25];
  new Random().nextBytes(randomByteArray);

  new MockServerClient("localhost", 1080)
      .when(
          request().withPath("/some/path")
      )
      .error(
          error()
              .withDropConnection(true)
              .withResponseBytes(randomByteArray)
      );
  ```

  ```bash REST API theme={null}
  curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
      "httpRequest": { "path": "/some/path" },
      "httpError": {
          "dropConnection": true,
          "responseBytes": "eQqmdjEEoaXnCvcK6lOAIZeU+Pn+womxmg=="
      }
  }'
  ```
</CodeGroup>

`responseBytes` is a base64-encoded byte array.
