DEV Community

Cover image for How to Build a Blazing-Fast Blazor Blog with Cosmic
Sumit Kharche
Sumit Kharche

Posted on • Originally published at cosmicjs.com

7 3

How to Build a Blazing-Fast Blazor Blog with Cosmic

In this tutorial, I'm going to show you how to create a simple but blazing fast blog using Blazor WebAssembly, Tailwind CSS, and Cosmic. Without further ado, grab some coffee & let's build a cool app!

TL;DR

Prerequisites

  • Installed the latest .NET Core SDK.
  • Install the Blazor project templates
  • Cosmic account
  • Basic knowledge of Blazor

Let's get started with our technology stack.

What is Blazor?

Blazor is a .NET framework developed and maintained by Microsoft. It's been picking up steam over the last couple of years, and recently attracted quite a bit of attention in Spring of 2020 with the launch of Blazor WebAssembly - which is what we'll be using today. If you want to build an interactive web application using C# then you should definitely check Blazor.

According to Blazor's docs:

Blazor is a free and open-source web framework that enables developers to create web apps using C# and HTML. It is being developed by Microsoft. Blazor lets you build interactive web UIs using C# instead of JavaScript. Blazor apps are composed of reusable web UI components implemented using C#, HTML, and CSS. Both client and server code is written in C#, allowing you to share code and libraries. Blazor can run your client-side C# code directly in the browser, using WebAssembly. Because it's real .NET running on WebAssembly, you can re-use code and libraries from server-side parts of your application.

There are two ways to create Blazor apps:

  • Blazor Server
  • Blazor WebAssembly

So in this article, we are going to use Blazor WebAssembly - which is one way to host Blazor components client-side in the browser using a WebAssembly-based .NET runtime.

What about Cosmic?

Cosmic is a headless CMS that will enable us to build our application surprisingly quickly and deploy it to Netlifly in moments. Unlike traditional CMS, Cosmic offers us as the developers a lot of flexibility to develop this application how we please and take it to whatever hosting platform we wish. It is also very easy to store and retrieve data, which makes it perfect for building apps like this.

Creating Your Blog Bucket in Cosmic

To create a blog app we will require data. To manage and manipulate this data, we will be using the power of Cosmic buckets and objects. To get started:

  1. Create a free account on Cosmic. If this is your first time using Cosmic, you'll see a short tutorial which will introduce some of the data types we'll be using - buckets, objects, and metafields.

  2. Create a new empty bucket & name it blazor-blog. For each blog post, we will have three object types:

  • Title
  • Content
  • Image

So, go ahead and add these properties in your buckets along with some data for those objects. If you're having trouble with Buckets, Objects, or Metafields, go ahead and read the Getting Started page really quickly for some startup instructions, then come on back to this article.

Creating Your Blazor WebAssembly app

You can now create and run your first Blazor WebAssembly app by running:

dotnet new blazorwasm -o BlazorCosmicBlog --pwa
cd BlazorCosmicBlog
dotnet run
Enter fullscreen mode Exit fullscreen mode

Now open the https://localhost:44346/ to see the default blazor app.

new-app

To fetch blog posts saved in Cosmic we require a Cosmic bucket Slug. Go to Cosmic -> Bucket -> Settings -> Basic Settings and copy the Bucket Slug.

api

To store the slug, create a new file appsettings.josn in the wwwroot folder and add the below code:

{
"AppSettings": {
"COSMIC_BUCKET_SLUG": "" // replace your bucket slug
}
}

Now open the program.cs file and add the below code to load the appsettings.json file.

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using BlazorCosmicBlog.Models;
namespace BlazorCosmicBlog
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
ConfigureServices(builder.Services);
await builder.Build().RunAsync();
}
public static void ConfigureServices(IServiceCollection services)
{
// Example of loading a configuration as configuration isn't available yet at this stage.
services.AddSingleton(provider =>
{
var config = provider.GetService<IConfiguration>();
return config.GetSection("App").Get<AppSettings>();
});
}
}
}
view raw Program.cs hosted with ❤ by GitHub

We are using Tailwind CSS to style our application, so let's add CDN into the index.html file.

<link https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
Enter fullscreen mode Exit fullscreen mode

Building Our Blog Pages

First, we are building the main category page where we can show all the blog posts. Create a folder called Models and add class to store posts.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorCosmicBlog.Models
{
public class Post
{
public string _id { get; set; }
public string Slug { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Published_at { get; set; }
public PostMetadata Metadata { get; set; }
}
public class PostMetadata
{
public Hero hero { get; set; }
}
public class Hero
{
public string url { get; set; }
public string imgix_url { get; set; }
}
}
view raw Post.cs hosted with ❤ by GitHub

Go to Pages folder and open Index.razor component and add the below code to show list of posts fetching from Cosmic.

@page "/"
@inject HttpClient Http
@using Microsoft.Extensions.Configuration;
@using Models
@inject IConfiguration Configuration
@if (allPosts == null)
{
<p><em>Loading...</em></p>
}
else
{
<section class="text-gray-700 body-font">
<div class="container px-5 pb-24 mx-auto">
<div class="flex flex-wrap -m-4">
@foreach (var post in allPosts.objects)
{
<div class="p-4 md:w-1/3">
<div class="h-full border-2 border-gray-200 rounded-lg overflow-hidden">
<img class="lg:h-48 md:h-36 w-full object-cover object-center" src="@post.Metadata.hero.imgix_url?w=720&h=400" alt="blog">
<div class="p-6">
<h1 class="title-font text-lg font-medium text-gray-900 mb-3">@post.Title</h1>
<div class="flex items-center flex-wrap ">
<NavLink href="@($"post/{post.Slug}")">
<a class="text-indigo-500 inline-flex items-center">
Read More
<svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-4 h-4 ml-2" viewBox="0 0 24 24">
<path d="M5 12h14M12 5l7 7-7 7"></path>
</svg>
</a>
</NavLink>
</div>
</div>
</div>
</div>
}
</div>
</div>
</section>
}
@code {
private AllPost allPosts = null;
protected override async Task OnInitializedAsync()
{
string cosmic_bucket_slug = Configuration["AppSettings:COSMIC_BUCKET_SLUG"];
var url = "https://api.cosmicjs.com/v1/{COSMIC_BUCKET_SLUG}/objects?pretty=true&hide_metafields=true&type=posts";
allPosts = await Http.GetFromJsonAsync<AllPost>(url.Replace("{COSMIC_BUCKET_SLUG}", cosmic_bucket_slug));
}
public class AllPost
{
public int limit { get; set; }
public int total { get; set; }
public Post[] objects { get; set; }
}
public class PostObject
{
public List<Post> _items { get; set; }
}
}
view raw Index.razor hosted with ❤ by GitHub

Let's run the app to see the output.

index

Looking good! Create a new component into the Pages folder called PostDetails.razor which shows the details of posts when we click on Read More button from all post pages.

@page "/post/{Slug}"
@inject HttpClient Http
@inject NavigationManager NavigationManager
@using System.Text.Json.Serialization
@using Models
@if (postDetails != null && postDetails.post == null)
{
<p><em>Loading...</em></p>
}
else
{
<section class="text-gray-700 body-font">
<div class="container mx-auto flex px-5 pb-24 items-center justify-center flex-col">
<h1 class="title-font sm:text-4xl text-3xl mb-4 font-medium text-gray-900">@postDetails.post.Title</h1>
<img class=" mb-10 object-cover object-center rounded" alt="hero" src="@postDetails.post.Metadata.hero.imgix_url">
<div class=" w-full">
<div class="mb-8 leading-relaxed">@((MarkupString)postDetails.post.Content)</div>
</div>
<div class="p-2 w-full">
<button class="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg" @onclick="NavigateToIndexComponent">Back</button>
</div>
</div>
</section>
}
@code {
[Parameter] public string Slug { get; set; }
private PostDetail postDetails = new PostDetail();
protected override async Task OnInitializedAsync()
{
var url = $"https://api.cosmicjs.com/v1/03ed2a30-a597-11e9-8965-1ff07c75b41d/object/{Slug}?pretty=true&hide_metafields=true";
postDetails = await Http.GetFromJsonAsync<PostDetail>(url.Replace("{Slug}", Slug));
postDetails.post.Metadata.hero.imgix_url = postDetails.post.Metadata.hero.imgix_url + "?w=720&h=600";
}
private void NavigateToIndexComponent()
{
NavigationManager.NavigateTo("");
}
public class PostDetail
{
[JsonPropertyName("object")]
public Post post { get; set; }
}
}

Now run the app and click on Read More button from the Home page to see post details.

post-details

That's it! All our core features are working. We have successfully created a blog application using Blazor and Cosmic. Now it's just up to your content team members to add some blog posts to it.

Deploying Your Blazor Blog to Hosting Platforms

We can now deploy our application on any hosting platform. We are deploying our app on Netlify using Github Actions.

  1. Commit your code to the GitHub repository.
  2. Login to Netlify and create a new site.
  3. We need a Personal Access Token and Site Id to deploy our app to netlify. So Go to Profile and generate Personal Access Token.

netlify1

  1. Go to your site -> Site details
    netlify2

  2. Go to your repository Settings -> Secrets and above two secrets:
    netlify3

  3. Click on Actions -> New Workflow and select .NET Core template. After that add the below code to yml file.

  4. name: .NET Core
    on:
    push:
    branches: [ master ]
    pull_request:
    branches: [ master ]
    jobs:
    build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Setup .NET Core
    uses: actions/setup-dotnet@v1
    with:
    dotnet-version: 3.1.301
    - name: Install dependencies
    run: dotnet restore
    - name: Build
    run: dotnet build --configuration Release --no-restore
    - name: Publish Blazor webassembly using dotnet
    #create Blazor WebAssembly dist output folder in the project directory
    run: dotnet publish -c Release --no-build -o publishoutput
    - name: Publish generated Blazor webassembly to Netlify
    uses: netlify/actions/cli@master #uses Netlify Cli actions
    env: # These are the environment variables added in GitHub Secrets for this repo
    NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
    NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
    with:
    args: deploy --dir=publishoutput/wwwroot --prod #push this folder to Netlify
    secrets: '["NETLIFY_AUTH_TOKEN", "NETLIFY_SITE_ID"]'
    view raw dotnet-core.yml hosted with ❤ by GitHub
  5. Our blog app is successfully deployed to Netlify.
    netlify4

Conclusion

In this article, I have demonstrated you how to create a blogging application using Blazor and Cosmic. The Cosmic Community has a lot of examples on how to handle integration with email functions, download functions, and third-party platforms. If you're interested in building your own applications like this, get started by setting up your free account.

I really hope that you enjoyed this little app, and please do not hesitate to send me your thoughts or comments about what could I have done better.

If you have any comments or questions about building apps with Cosmic, reach out to us on Twitter and join the conversation on Slack.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
shaijut profile image
Shaiju T

Nice, 😄, but initial page load of Blazor is slow.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay