Adding a Favicon

Add a site icon (favicon.ico / PNG) so browsers display your brand in tabs and bookmarks. Kestrun provides Add-KrFavicon to register a favicon quickly without manually mapping a route.

Prerequisites: see Introduction.

Full source

File: pwsh/tutorial/examples/3.4-Add-FavIcon.ps1

<#
    Sample Kestrun Server on how to add a favicon.
    This example demonstrates how to configure a favicon in a Kestrun server.
    FileName: 3.4-Add-FavIcon.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 a file server with browsing enabled
Add-KrFileServerMiddleware -RequestPath '/' -RootPath '.\Assets\wwwroot' -EnableDirectoryBrowsing -ServeUnknownFileTypes

# Add a favicon
Add-KrFaviconMiddleware -IconPath '.\Assets\favicon.png'

# Enable Kestrun configuration
Enable-KrConfiguration


# Start the server asynchronously
Start-KrServer

Step-by-step

  1. Initialize root: Initialize-KrRoot -Path $PSScriptRoot.
  2. Server + listener: New-KrServer; Add-KrEndpoint -Port 5000 -IPAddress Loopback.
  3. File server: Add-KrFileServer -RequestPath '/' -RootPath '.\\Assets\\wwwroot' -EnableDirectoryBrowsing -ServeUnknownFileTypes.
  4. Favicon: Add-KrFavicon -IconPath '.\\Assets\\favicon.png' registers the icon.
  5. Apply config + start: Enable-KrConfiguration; Start-KrServer.

Check response headers for a valid Content-Type like image/x-icon or image/png.

Try it

Save the sample locally so it’s easy to run. Copy the contents of pwsh/tutorial/examples/3.4-Add-FavIcon.ps1 into a new file in an empty working folder (for example, Add-FavIcon.ps1), then open a browser to http://127.0.0.1:5000/ you should see the favicon on the browser tab.

Troubleshooting

Symptom Cause Fix
404 for favicon.ico Wrong -IconPath or file missing Ensure path is correct relative to root; confirm file exists.
Browser still shows old icon Browser cache Hard refresh, open dev tools, or change icon filename.
Incorrect MIME type Unusual extension Use .ico or .png for best compatibility.
Icon looks blurry Low resolution Provide at least 32x32 (or multi-size ICO).

References


Previous / Next

Go back to Static Route Overrides or continue to File Server Caching Headers.