As with any other SPA framework, you can deploy Blazor WASM in Github Pages! Today I’ll be showing you step by step how to do so. We will be using GitHub Actions to automate the deployment process.
Let’s begin with the most important file that lets a SPA work on GitHub Pages, the
As you know, SPAs only have one entry file, which is the
mywebsite.com/page1) won’t work, because there is no
GitHub Pages will try and return a 404 status code with an error page. The good thing is that it can be customized! Let’s go ahead and add a custom
404.html in our wwwroot folder (taken from spa-github-pages).
There are two important things to note here, which are explained very well by the description:
- An url like
https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomeswill become
https://username.github.io/repo-name/?p=/one/two&q=a=b~and~c=d#qwe. Notice that the path
/one/twobecomes a parameter, so this essentially redirects to the
index.htmlwith extra parameters.
- Pay attention to the comment about
segmentCount, you might need to change it to
As we saw in the previous section, the
404.html file adds a
p parameter that contains the page the user asked for. We would need to use that in our
index.html file. Let’s modify our wwwroot/index.html file to add this script:
GitHub Pages uses Jekyll, and by default, directories that start with an underscore are treated specially. This means that our two important folders,
_framework won’t get served.
To fix this, we only need to create the empty file wwwroot/.nojekyll.
Now for the deployment part!
To keep the repository clean, we will be deploying the website in a separate branch
gh-pages. Let’s create an empty one now:
Next, configure GitHub Pages to use this branch in the repository:
Let’s go over this step by step:
- Publish app: We publish the project using
dotnet publish. If your project is in a subfolder, add
cd Path/To/Project &&in the start.
- Rewrite base href: In the
index.htmlfile, there is
<base href="/" />. We need to change the
/into our GitHub Repository name in order for the navigation to work.
- GitHub Pages: Lastly, we push our published website into the
If you configured everything right, running this should deploy the project successfully!
- Steve Sanderson’s helpful repository BlazorOnGitHubPages.
- rafrex’s famous repository spa-github-pages.
As you can see, it’s fairly easy to deploy a Blazor Wasm project in GitHub Pages. You can, if you want to, skip the GitHub Actions step and publish the project locally, then uploading it whenever needed. But you might as well use the free GitHub Actions minutes!
Hope you liked the post, see you next time.