Taking Nuxt to the Backend with Supabase 🚀
Tags: vue, nuxt, typescript, javascript
Published: 2024-01-08 09:21:12

Two months ago, I was giving a talk at Nuxt Nation which is currently my favourite online conference related to Vue.js. This time, I decided to speak about topic that was not fully related to what I am doing with Nuxt on a daily basis but rather an interesting use case.

Instead of using Frontend Framework as it was supposed to be used (in the Frontend), I decided to instead use it as a backend and more specifically, a microservice that I was later using to fetch the data from. The recording of my talk is available below:

{% embed https://youtu.be/FiPBKZTIDEQ %}

And if you would like to see the GitHub repository for this project, check out the following link:

https://github.com/Baroshem/nuxt-backend

Below, I have added some definitions and items from my slide to allow you to better understand the concept :)

Enjoy!

## 🤔 Using Nuxt on the Backend

Nuxt 3 is powered by a new server engine, Nitro ⚡️:

* Cross-platform support for Node.js, Browsers, service-workers and more.
* Serverless support out-of-the-box.
* API routes support.
* Automatic code-splitting and async-loaded chunks.
* Hybrid mode for static + serverless sites.
* Development server with hot module reloading.

Server API endpoints and Middleware are added by Nitro that internally uses h3 that provides:

* Handlers can directly return objects/arrays for an automatically-handled JSON response
* Handlers can return promises, which will be awaited (res.end() and next() are also supported)
* Helper functions for body parsing, cookie handling, redirects, headers and more

This server API allows us to write API endpoints in the server directory like following:

```ts
// server/api/hello.ts

export default defineEventHandler((event) => {
  return {
    hello: 'world'
  }
})
```

And then, use it in your Frontend like following:

```vue
// pages/index.vue

<script setup lang="ts">
const { data } = await useFetch('/api/hello')
</script>

<template>
  <pre>{{ data }}</pre>
</template>
```

We can utilize this fullstack concept by building a microservice but first lets learn what this concept is.

### What are microservices?

Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are:

* Independently deployable
* Loosely coupled
* Organized around business capabilities
* Owned by a small team

The microservice architecture enables an organization to deliver large, complex applications rapidly, frequently, reliably and sustainably - a necessity for competing and winning in today’s world.

### What are the benefits of using Nuxt on the backend?

Using Nuxt on the backend may seem strange at first but take a look at following pros: 

* As Frontend developers, we don’t like to touch the infrastructure
* Simple deployment for many popular hosting providers
* No extensive configuration needed
* Usage of popular and widely used Nuxt modules

Supabase helped Frontend devs work with databases and auth. Nuxt allows extend it even further to infrastructure allowing to streamline dev process by a mile!

Using Nuxt here, allows us to utilize the concept of Micromodules (Microfrontend + Microservice) that comes with following pros:

* Separation of concerns
* Ability to call One Nuxt Backend from another Nuxt Frontend
* One module that handles both UI and Logic
* One repository for certain domain of your app

## Using Supabase as our database

In this example, I decided to use Supabase due to simplicity of usage and great Developer Experience. The usage of Supabase in Nuxt is really straightforward.

First we need to install the module and add it to the `nuxt.config.ts` file:

```ts
export default defineNuxtConfig({
  devtools: { enabled: true },
  modules: ['@nuxtjs/supabase', 'nuxt-security'],

  security: {
    corsHandler: {
        origin: '*'
    }
  },
})
```

As I needed to share resources with cross origins, I decided to also add [Nuxt Security](https://nuxt-security.vercel.app/)

Next, we need to create a new Event Handler:

```ts
import { serverSupabaseClient } from "#supabase/server";

export default defineEventHandler(async (event) => {
  const query = getQuery(event);

  const name = query.name;

  const client = await serverSupabaseClient(event);

  return !name
    ? (await client.from("cats").select("*")).data
    : (await client.from("cats").select("*").eq("name", name).single()).data;
});
```

This event handler basically allows to fetch either one cat by a name query or all cats from Supabase.

Finally, to fetch the data from another application, we need to use following code:

```vue
<template>
  <div>
    <ul>
      <li v-for="cat in cats" :key="cat.id">
        <img :src="cat.image" />
        <h2>{{ cat.name }}</h2>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
const cats = ref();
onMounted(async () => {
  // https://nuxt-backend.vercel.app/
  const res = await $fetch("http://localhost:3001/api/cat", {
    method: "GET",
  });

  cats.value = res;
});
</script>
```

And that's it! We now have a simple microservice architecture by using Nuxt and Supabase.

## 📖 Learn more 

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this [link](https://vueschool.io/courses?friend=baroshem) or by clicking the image below:

[![Vue School Link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i662jpyni4zs2dlaeud1.png)](https://vueschool.io/courses?friend=baroshem)

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

## ✅ Summary

Well done! You have just learned how you could use Nuxt as the Backend with the usage of Supabase.

Take care and see you next time!

And happy coding as always 🖥️