# Middleware

Middleware is run during each HTTP request by the PowerShell Universal server. It gives you the opportunity to customize features of the request like status code, headers and cookies.

{% hint style="warning" %}
Since middleware is executed during each request, performance should be a consideration when implementing custom middleware.
{% endhint %}

### Middleware.ps1

The middleware.ps1 file can be created in the `.universal` folder using the `New-PSUMiddleware` cmdlet.

Each middleware instance receives a [HttpContext](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/use-http-context?view=aspnetcore-7.0) object when it is called. The middleware should return true or false. If false is returned, the middleware will stop passing the context to additional items on the middleware pipeline.

The below example adds a test cookie to the response.

```powershell
New-PSUMiddleware -Name 'Middle' -ScriptBlock {
    param($HttpContext)
    $HttpContext.Response.Cookies.Append('X-Test', "Test")
    $true
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.powershelluniversal.com/platform/middleware.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
