Static Route Overrides

Inject dynamic responses at specific file paths under a static directory.

Prerequisites: see Introduction.

Full source

File: pwsh/tutorial/examples/3.3-Static-OverrideRoutes.ps1

<#
    Sample Kestrun Server on how to use static routes.
    These examples demonstrate how to configure static routes in a Kestrun server.
    FileName: 3.3-Static-OverrideRoutes.ps1
#>

param(
    [int]$Port = 5000,
    [IPAddress]$IPAddress = [IPAddress]::Loopback
)

# Initialize Kestrun root directory
# the default value is $PWD
# This is recommended in order to use relative paths without issues
Initialize-KrRoot -Path $PSScriptRoot

# Create a new Kestrun server
New-KrServer -Name 'Simple Server'

# Add a listener on the configured port and IP address
Add-KrEndpoint -Port $Port -IPAddress $IPAddress

# Add the PowerShell runtime


# Add a static files service
Add-KrStaticFilesMiddleware -RequestPath '/assets' -RootPath '.\Assets\wwwroot'

# Add a static map override
# Note: register the static files middleware first, then register the dynamic
# route with `Add-KrMapRoute` to override a specific physical path. The last
# registration wins when a path conflict occurs.
Add-KrMapRoute -Path '/assets/override/pwsh' -ScriptBlock {

    $data = @{
        status = 'ok'
        message = 'Static override works!'
    }

    Write-KrJsonResponse -InputObject $data
}

# Enable Kestrun configuration
Enable-KrConfiguration


# Start the server asynchronously
Start-KrServer

Step-by-step

  1. Initialize root: Initialize-KrRoot -Path $PSScriptRoot for reliable relative paths.
  2. Create server and listener: New-KrServer; Add-KrEndpoint -Port 5000 -IPAddress Loopback.
  3. Register static files: Add-KrStaticFilesService -RequestPath '/assets' -RootPath '.\\Assets\\wwwroot'.
  4. Add override: Add-KrMapRoute -Path '/assets/override/pwsh' with a script block returning JSON.
  5. Apply config and start: Enable-KrConfiguration; then Start-KrServer.

Try it

Save the sample locally so it’s easy to run. Copy the contents of pwsh/tutorial/examples/3.3-Static-OverrideRoutes.ps1 into a new file in an empty working folder (for example, override-routes.ps1), then run:

# From your working folder
pwsh .\override-routes.ps1
curl http://127.0.0.1:5000/assets/override/pwsh
Invoke-RestMethod -Uri 'http://127.0.0.1:5000/assets/override/pwsh'

Expected JSON:

{ "status": "ok", "message": "Static override works!" }

Why use an override?

  • Add a health or status JSON under a static prefix (e.g., /assets/status).
  • Replace a generated config file without changing the build output.
  • Rapid prototyping: deliver dynamic snippets alongside static SPA assets.

Behavior and precedence

  • Path match is exact against the full request path.
  • An override takes precedence over a file of the same path under the static root.
  • If no override exists the physical file (if present) is served.

Precedence note

Register the static files service first (for example, Add-KrStaticFilesMiddleware), then register any dynamic routes that should override specific static file paths using Add-KrMapRoute. In case of a path conflict the last registration wins — registering the dynamic route after the static service ensures the dynamic handler is executed instead of serving the physical file.

(Optional) Create a file to test precedence

Create a physical file at Assets/wwwroot/override/pwsh and restart the script. The override still wins. Remove the override line (or comment it out), restart, and the physical file will be served instead.

Best practices

  • Keep override script blocks small and fast (avoid long-running logic).
  • Use descriptive paths (e.g., /assets/health, /assets/meta/info).
  • Avoid large dynamic payloads; prefer a dedicated API route (Add-KrMapRoute) for complex behavior.
  • Document override locations so future maintainers understand why a file path is dynamic.

Troubleshooting

Symptom Cause Fix
Exception when adding override Added after Enable-KrConfiguration Move Add-KrMapRoute earlier (before enabling).
404 Not Found Path mismatch or missing static base Verify path starts with mounted prefix /assets and static service registered.
Physical file served instead of JSON Override removed or path typo Re-add override with correct path; ensure leading /.
Unexpected content type Response helper not used Use Write-KrJsonResponse / Write-KrTextResponse as appropriate.

When to choose an override vs a normal route

Scenario Dynamic file-path route (under static prefix via Add-KrMapRoute) Standard route (Add-KrMapRoute)
Integrate dynamic JSON under static prefix Possible (but separate path tree)
Need route outside static prefix ✖ (not needed)
Replace/augment a single file path Indirect (different URL)
Many related dynamic endpoints Less ideal ✔ (group them normally)

References


Previous / Next

Go back to File Server & Directory Browsing or continue to Adding a Favicon.