• Blazor
  • Code Snippet
  • HTTP
  • User Agent

Code Snippet: Conditional User Agent Logic with Blazor

Below is a quick snippet of how to render your Blazor application without JavaScript, so when an bot comes in it will have less assets to deal with on the Request.

Snippet

The snippet uses a regex to match on some standard bot User Agents string. If the user agent does not match our bot regex it will include the JavaScript for Blazor Server.

@* _Host.cshtml *@

@page "/"
@namespace Example.Pages
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.Net.Http.Headers
@using System.Text.RegularExpressions
@{
    Layout = null;
    var userAgent = Request.Headers[HeaderNames.UserAgent];
    // Using regex we look for some standard User Agents that are bots
    var isNotBotAgent = !Regex.IsMatch(
        userAgent,
        @"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google",
        RegexOptions.IgnoreCase
    );
}

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="~/" />

    <link href="css/site.css" rel="stylesheet" />
    <link href="CodyAnhorn.Tech.styles.css" rel="stylesheet" />
</head>
<body>
    <component type="typeof(App)" render-mode="ServerPrerendered" />

    @if (isNotBotAgent)
    {
        @* We are only including the Blazor Server js when we are not a bot. *@
        @* This makes it so the site is just a normal Server Side Render application, that works better with bots and user that are not using JavaScript. *@
        <script src="_framework/blazor.server.js"></script>
    }

</body>
</html>