Dark mode detection middleware in ASP.NET Core without any JS #62700
              
                Unanswered
              
          
                  
                    
                      afshin29
                    
                  
                
                  asked this question in
                Show and tell
              
            Replies: 0 comments
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Uh oh!
There was an error while loading. Please reload this page.
-
Modern chromium browsers have dark mode detection capabilities built-in and they can let the web server know of user's dark mode preferences. I recently used this new modern feature in my side project and I would like to share it here with the community. Your feedback is appreciated.
In C# we can create the following middleware:
And the following extension for it:
In F#:
Next we need an extension to check if a request is in dark mode. we have three ways to know, if we have set a cookie (it means user has changed the default detected theme), then we check the cookie's value, let's say "1" means use dark mode and other values mean don't. If we haven't set a cookie then we use the available header:
In C#:
In F#:
And that's it! We can use these to set the correct CSS class or the correct CSS link in our HTML rendering logic. For example in Bootstrap 5 using Razor:
Or in Giraffe View Engine:
Note: both JS and CSS have mechanisms to detect dark mode, but, they run on the browser, which is too late for server side rendering logic to use the correct class or asset.
Beta Was this translation helpful? Give feedback.
All reactions