Prerequisites
Previously, I cover what Heroku is and how to use it for free for your blazor app. You need to go throug the tutorial and get familiar with steps how to create blazor app on heroku.
Database
Today, I want to talk about database, which is must option to have in most cases for your apps. Fortunatelly, heroku offers free postgresql, which has limitations, but enough for you to start.
Create database
Open your app on heroku and click Configure Add-ons
. Then type “heroku” into search input and select “Heroku postgres”
Select free plan.
Now, if you go to settings
tab and click Reveal Config Vars
You can see that you have DATABASE_URL
variable. It is environment variable for your app and it contains connection string to database.
However, it is not the same connection string as we used to have in our application settings. So we have to change it in the following way
private string _getConnectionString(string envVarName)
{
var herokuConnectionString = Configuration[envVarName];
if (string.IsNullOrEmpty(herokuConnectionString)) return null;
var databaseUri = new Uri(herokuConnectionString);
var userInfo = databaseUri.UserInfo.Split(':');
var builder = new NpgsqlConnectionStringBuilder
{
Host = databaseUri.Host,
Port = databaseUri.Port,
Username = userInfo[0],
Password = userInfo[1],
Database = databaseUri.LocalPath.TrimStart('/'),
SslMode = SslMode.Require,
TrustServerCertificate = true
};
return builder.ToString();
}
We can use this method to get connection string for EF core:
services.AddDbContext<PostgreDbContext>(options =>
options.UseNpgsql(_getConnectionString("DATABASE_URL")));
That is all you need to do to use free postgresql on heroku. You have 10 000 rows and 20 connection limit for free plan. You can get acquainted of all limitations here.
Conclusion
Heroku offers you free plan not only for your web app, but also worker, postgres database and redis storage.