Use Pocketbase — Open Source Backend

Sneh Mehta
Level Up Coding
Published in
6 min readJan 13, 2023

--

To be precise, when you should use Pocketbase instead of Firebase.

Okay, so you are at the point in life where you have to build a product that requires a backend. Now there are many ways to solve the problem like building one from scratch or picking up some backend as a service provider like Firebase (GCP), Amplify (AWS), Supabase(Open-source) or our topic of today PocketBase.

The article will not compare all backend-as-a-service (BaaS) providers, but will focus specifically on Firebase and Pocketbase and what more can you can expect from this article.

  • When to select Firebase and when Pocketbase.
  • Short coming of Pocketbase and ways around it
  • Pocketbase as a Framework.
  • Deploying Pocketbase.
  • Conclusion

Instead of going into the pros and cons of each platform in detail, the article will provide a brief overview of the context in which each platform might be useful.

Firebase

Make your app the best it can be

I have had positive experiences with Firebase and have successfully built and sold products using it. Firebase is generally a reliable and comprehensive platform that offers a range of useful features, including authentication, a NoSQL real-time database, custom functions for business logic, file storage, and hosting. It also has a well-designed client-side SDK. and can’t forget the easiness of getting started with firebase which requiring only a few clicks to set up.

One of the limitations of Firebase is that it does not currently offer advanced aggregation queries such as SUM or AVG. The Firebase team has recently introduced the COUNT query, but this may not meet all needs for aggregation.

If your use-case requires this queries then use Pocketbase.

Another issue with Firebase is its limited extensibility. While it does offer services like cloud functions and extensions to help bridge the gap, these may not be as flexible as Pocketbase’s extensibility. In comparison, Pocketbase offers a higher level of customization and flexibility for building custom APIs and routes.

If your use-case requires more extensibility i.e third party integrations, custom business logic, transaction compliance then pick Pocketbase.

Firestore, the database used by Firebase, is a proprietary platform and does not provide any tools for exporting or importing data outside of BigQuery. This can make it difficult to migrate data to or from Firestore, potentially causing issues for developers.

Data migration is top priority when then use Pocketbase.

Pocketbase

Open Source backend for your next SaaS and Mobile app in 1 file” written in Go.

Pocketbase Admin panel

Things available out of the box

  • Realtime database powered by embedded SQLite in WAL mode.
  • Authentication with email and OAuth2.
  • File storage with S3.
  • Client SDK for Dart and Javascript.

If you want to try out Pocketbase and see how it works, you can explore the demo project provided by the platform. This can give you a good idea of the capabilities of Pocketbase and how it compares to other BaaS platforms.

If you want a more in-depth experience with Pocketbase, you can consider using pockethost and deploying it on fly.io. This will allow you to fully test out Pocketbase and see how it performs in a real-world scenario.

True power

It lies in using Pocketbase as a framework. This way you can have all the goodies of things included in the box and flexibility to create something of your own.

func main() {
app := pocketbase.New()

if err := app.Start(); err != nil {
log.Fatal(err)
}
}

Probably you might see Go code but don’t shy away, Go is a simple programming language that is easy to learn, even for those who are new to it. It is designed to have fewer concepts to learn than some other languages, which means it can be a good choice for those who want to get up to speed quickly.

Pocketbase has done a lot of the heavy lifting, so you don’t have to write as much code when using it, which can make it easier to develop custom extendable APIs.

Let me show you some of example.

Custom API route

Aggregation query are not supported out of the box, but we can write a custom route where we can run our own SQL query. Pocketbase behind the scene uses echo so when creating custom routes we can check echo’s documentation.

// inside main

app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/get_monthly_limit",
Handler: func(c echo.Context) error {

result := struct {
TotalLimit int `db:"totalLimit" json:"totalLimit"`
}{}

app.Dao().DB().Select("SUM(monthlyLimit) as totalLimit").From("categories").One(&result)
return c.JSON(http.StatusOK, result)
},
})
return nil
})

First time it might seem intimidating but I save read through it and you’ll understand, here let me show you.

  • First line is Pocketbase’s way of adding things to the framework which is by using onBeforeServe
  • Second the thing we want to add is add new Route to echo’s Router
  • Now our specific implementation starts with is easy to follow.

Send Notification using firebase

We can send notification using firebase Admin sdk for Go.

With two little steps:

  • Initialize firebaseApp
  • Setup up a custom route or hook which you can find here.
// In the main
firebaseApp, err := initFirebaseApp()

func initFirebaseApp() (*firebase.App, error) {
opt := option.WithCredentialsFile("/etc/secret/service_account.json")

app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return nil, err
}
return app, nil

}
ctx := context.Background()
messagingClient, _ := firebaseApp.Messaging(ctx)


e.Router.AddRoute(echo.Route{
Method: http.MethodPost,
Path: "/api/send_notification",
Handler: func(c echo.Context) error {

token := c.FormValue("token")

message := &messaging.Message{
Token: token,
Notification: &messaging.Notification{
Title: "hello",
Body: "Golang",
},
}
response, err := messagingClient.Send(ctx, message)
if err != nil {
return c.String(http.StatusPreconditionFailed, "Something went wrong")
}

return c.String(http.StatusOK, response)
},
})

Run script in some periodic time

Register a new command with app.RootCmd.AddCommand internally spf13/cobra is being used. So you can check their documentation.

app.RootCmd.AddCommand(&cobra.Command{
Use: "fetch_something",
Run: func(command *cobra.Command, args []string) {
log.Println("Fetched something !")
},
})

Run it by calling ./main fetch_something and schedule it using crontab. Awesome right.

Deployment

If you are on only linux distribution you can run go build main.go and an excecutable will get generated. Simply copy to server using scp or rsync.

// in your local machine
scp $pathToYourExecutable root@$yourServerIP:/home/
// after ssh-ing to your server
/home/$yourExcutable serve

Great job on deploying your backend!

However, if you close your SSH terminal, your server will also go down. To prevent this from happening, you can set up a systemd service to keep your server running in the background. You can find more information on how to do this in the official documentation.

Alternatively, if you are using Windows, you can clone the source code onto the server, build the executable, and then run it using systemd and nginx. To do this,

  • First install the Go programming language.
  • Then, you can clone the repository and build the executable using the Go compiler.
  • Finally, you can set up systemd and nginx to keep your server running in the background again same documentation.

Conclusion

Pocketbase and Firebase are great tools for quickly building and deploying a minimum viable product or testing product-market fit. While they can be useful for getting a product off the ground quickly, it is important to keep in mind that they may not be the best solution for long-term, high-scale projects. If your app experiences explosive growth, you may need to build a custom backend from scratch or hire someone to do it for you.

It’s important to choose the right tools for your project, and BAAS platforms like Pocketbase and Firebase can be great choices for getting started quickly. Just be sure to consider the potential for future growth and the ability to migrate to a custom backend if necessary. Technology is a tool to help you build something valuable, and it’s up to you to choose the right one for your needs

I am technical geek who likes to try new things and learning to share it with the world, if you have any suggestions or find yourself in difficulty feel free to reach out on twitter.

Until next time.

--

--

Software developer & consultant. Sharing what I am learning every week.