• Documentation
  • /
  • Remix Firebase
  • /
  • Tutorial: Tasks Application

Tutorial: Tasks Application

Full walkthrough to building an application with Makerkit

This tutorial is a comprehensive guide to getting started with the Remix and Firebase template to build a SaaS, from fetching the repository to deploying the application.

By the end, you'll have a fully working application with the minimum basics a SaaS needs:

  1. Landing Page and Marketing pages (blog, documentation)
  2. Authentication (sign in, sign up)
  3. Payments (Stripe)
  4. Profile and Organization management

Prerequisites

To get started, you're going to need some things installed:

  1. Git
  2. Node.js version (>=16.0.0)
  3. npm 7 or greater
  4. A code editor (VSCode, WebStorm)
  5. If you'd like to deploy your application, you'll also want an account on Vercel.

Experience with React, TypeScript/JavaScript, and Firebase would be advantageous but not strictly required. The codebase can also serve as a way to learn these topics more in-depth.

If you have all the above installed, I guess we can get started!

Generating a new Makerkit Project

Assuming you have access to the repository, open your terminal and run this command (replace tasks-app with your name of choice):

git clone --depth=1 https://github.com/makerkit/remix-firebase-saas-kit
tasks-app

Once completed, we'll change into the tasks-app directory, and then we will install the Node modules:

cd tasks-app
npm i

Reinitialize Git

As the Git repository's remote points to Makerkit's original repository, you can re-initialize it and set the Makerkit repository as upstream:

rm -rf .git
git init
git remote add upstream https://github.com/makerkit/remix-firebase-saas-kit
git add .
git commit -a -m "Initial Commit"

By adding the Makerkit's repository as upstream remote, you can fetch updates (after committing your files) by running the following command:

git pull upstream main --allow-unrelated-histories

Installing Firebase

Additionally, you may want to install the firebase-tools package globally on your system:

npm i -g firebase-tools

If you have already installed it, ensure you're running its latest (or recent) version.

Perfect! Now you can fire up your IDE and open the tasks-app project we just created.

Project Structure

When inspecting the project structure, you will find something similar to the below:

tasks-app
├── README.md
├── @types
├── src
│   ├── components
│   ├── core
│   ├── lib
│   └── routes
        └── __app
        └── __site
        └── auth
        └── invite
        └── onboarding
│       └── root.tsx
├── package-lock.json
├── package.json
├── public
│   └── favicon.ico
└── tsconfig.json

NB: we omitted a lot of the files for simplicity.

Let's take a deeper look at the structure we see above:

  • src/core: this folder contains reusable building blocks of the template that are not related to any domain. This includes components, React hooks, functions, and so on.
  • src/components: this folder contains the application's components, including those that belong to your application's domain. For example, we can add the tasks components to src/components/tasks.
  • src/lib: this folder contains the business logic of your application's domain. For example, we can add the tasks hooks to write and fetch data from Firestore in src/lib/tasks.
  • src/routed: this is Remix folder where we add our application routes.

Don't worry if this isn't clear yet! We'll explain where we place our files in the sections ahead.

Running the project

When we run the stack of a Makerkit application, we will need to run a few commands before:

  1. Remixs: First, we need to run the Remix development server
  2. Firebase: We need to run the Firebase Emulators. The emulators allow us to run a fully-local Firebase environment.
  3. Stripe CLI (optional): If you plan on interacting with Stripe, you are also required to run the Stripe CLI, which allows us to test the webhooks from Stripe against our local server.

Running the Remix development server

Run the following command from your IDE or from your terminal:

npm run dev

This command will start the Remix server at localhost:3000. If you navigate to this page, you should be able to see the landing page of your application:

Running the Firebase Emulators

To interact with Firebase's services, such as Auth, Firestore, and Storage, we need to run the Firebase emulators. To do so, open a new terminal (or, better, from your IDE) and run the following command:

npm run firebase:emulators:start

If everything is working correctly, you will see the output below:

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ localhost:9099 │ http://localhost:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ localhost:8080 │ http://localhost:4000/firestore │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Pub/Sub        │ localhost:8085 │ n/a                             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Storage        │ localhost:9199 │ http://localhost:4000/storage   │
└────────────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500, 9150

By default, we run the emulator for the following services: Authentication, Firestore, and Storage. However, you can easily add Firebase Functions and PubSub.

Firebase Emulator UI

As you can see from the View in Emulator UI column, you have access to the Emulator UI, which helps you see and edit your Firebase Emulator data using a nifty UI that resembles the Firebase Console.

For example, to display the list of users that have signed up, navigate to the Authentication Emulator.

Makerkit's template adds some data to your project by default for testing reasons. In fact, the data you see is used to run the Cypress E2E tests. This is why you'll see some pre-populated data in your Firestore and Authentication tabs.

Running the Stripe CLI (optional)

Optionally, if you want to run Stripe locally (e.g., sending webhooks to your local server), you will also need to run the following command:

npm run stripe:listen

This command requires Docker, but you can alternatively install Stripe on your OS and change the command to use stripe directly.

The above command runs the Stripe CLI and will route webhooks coming from Stripe to your local endpoint. For example, in the Makerkit starter, this endpoint is /api/stripe/webhook.

When running the command, it will print a webhook key used to sign the messages from Stripe. You will need to add this key to your local environment variables file as below:

STRIPE_WEBHOOK_SECRET=<KEY>

The webhook printed should not change, so you may only need to do this the first time.

Project Configuration

Makerkit can be configured from a single place: the src/configuration.ts object. This file exports a constant we use throughout the project to read our application's settings.

We recommend adding additional configuration to this file rather than reading it directly from the environment variables. For example, assuming you rename one of your environment variables, you will only need to update it in one place. Additionally, it helps maintain your codebase more explicit and understandable.

We retrieve some of this file's configuration using environment variables: these help us swap and tweak our settings based on which environment we're using, such as the Firebase configuration.

For example, in your Vercel console, you could run multiple projects:

  • one for production
  • and one for staging

Here is what the configuration file looks like:

const configuration = {
  site: {
    name: 'Awesomely - Your SaaS Title',
    description: 'Your SaaS Description',
    themeColor: '#ffffff',
    themeColorDark: '#0a0a0a',
    siteUrl: process.env.SITE_URL as string,
    siteName: 'Awesomely',
    twitterHandle: '',
    githubHandle: '',
    language: 'en',
    convertKitFormId: '',
  },
  firebase: {
    apiKey: process.env.FIREBASE_API_KEY,
    authDomain: process.env.FIREBASE_AUTH_DOMAIN,
    projectId: process.env.FIREBASE_PROJECT_ID,
    storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.FIREBASE_APP_ID,
    measurementId: process.env.FIREBASE_MEASUREMENT_ID,
  },
  auth: {
    // Enable MFA. You must upgrade to GCP Identity Platform to use it.
    // see: https://cloud.google.com/identity-platform/docs/product-comparison
    enableMultiFactorAuth: false,
    // NB: Enable the providers below in the Firebase Console
    // in your production project
    providers: {
      emailPassword: true,
      phoneNumber: false,
      emailLink: false,
      oAuth: [GoogleAuthProvider],
    },
  },
  emulatorHost: process.env.EMULATOR_HOST,
  emulator: process.env.EMULATOR === 'true',
  production: process.env.NODE_ENV === 'production',
  paths: {
    signIn: '/auth/sign-in',
    signUp: '/auth/sign-up',
    emailLinkSignIn: '/auth/link',
    onboarding: `/onboarding`,
    appHome: '/dashboard',
    settings: {
      profile: '/settings/profile',
      authentication: '/settings/profile/authentication',
      email: '/settings/profile/email',
      password: '/settings/profile/password',
    },
    api: {
      checkout: `/api/stripe/checkout`,
      billingPortal: `/api/stripe/portal`,
    },
    searchIndex: `/public/search-index`,
  },
  navigation: {
    style: LayoutStyle.Sidebar,
  },
  appCheckSiteKey: process.env.APPCHECK_KEY,
  email: {
    host: '',
    port: 0,
    user: '',
    password: '',
    senderAddress: '',
  },
  emailEtherealTestAccount: {
    email: process.env.ETHEREAL_EMAIL,
    password: process.env.ETHEREAL_PASSWORD,
  },
  sentry: {
    dsn: process.env.SENTRY_DSN,
  },
  stripe: {
    plans: [
      {
        name: 'Basic',
        description: 'Description of your Basic plan',
        price: '$249/year',
        stripePriceId: 'basic-plan',
        features: [
          'Feature 1',
          'Feature 2',
          'common:plans.features.feature1'
        ],
      },
    ],
  }
};

Environment Variables

The starter project comes with three different environment variables files:

  1. .env: this is a shared environment file. Here, you can add variables shared across all the environments.
  2. .env.development: the configuration file loaded when running the dev command: by default, we add the Firebase Emulators settings to this file.
    • Use this file for your development configuration.
  3. .env.production: the configuration file loaded when running the build command locally or deployed to Vercel.
    • Use this file for your actual project's configuration (without private keys!).
  4. .env.test: this environment file is loaded when running the Cypress E2E tests. You would rarely need to use this.

Additionally, you can add another environment file named .env.local: this file is never added to Git and can be used to store the secrets you need during development.

Never ever add secrets to your .env files. It's not safe, and you risk leaking confidential data.

Instead, add your secrets using your Vercel Console, or use the .env.local file during development.

Tailwind CSS

This SaaS template uses Tailwind CSS for styling the application.

You will likely want to tweak the brand color of your application: to do so, open the file tailwind.config.js and replace the primary color (which it's blue by default):

extend: {
  colors: {
    primary: {
      ...colors.blue,
      contrast: '#fff',
    },
    black: {
      50: '#525252',
      100: '#363636',
      200: '#282828',
      300: '#222',
      400: '#121212',
      500: '#0a0a0a',
      600: '#040404',
      700: '#000',
    },
  },
},

To update the primary color, you can either:

  1. choose another color from the Tailwind CSS Color palette (for example, try colors.indigo, see the image below)
  2. define your own colors, from 50 to 900

The contrast color will be helpful to define the text color of some components, so tweaking it may be required.

Once updated, the Makerkit's theme will automatically adapt to your new color palette! For example, below, we set the primary color to colors.indigo:

Dark Mode

Makerkit ships with two themes: light and dark. The light theme is the default, but users can switch to the other, thanks to the component DarkModeToggle.

You can set the dark theme by default by adding the dark class to the Html component in _document.tsx:

<Html className='dark'>
...
</Html>

If you wish to only use the dark theme, you should remove the DarkModeToggle component from your application.

Loading video...

Alternatively, if you want to respect the user's system theme, update the Tailwind configuration and use the media strategy:

module.exports = {
  content: ['./src/**/*.tsx'],
  darkMode: 'media',
  // ...
}

Authentication

The Remix/Firebase template uses Firebase Auth to manage authentication into the internal application.

The kit supports the following strategies:

  1. Email/Password
  2. oAuth Providers such as Google, Twitter, Facebook, Microsoft, Apple, etc.
  3. Phone Number
  4. Email Link

You can choose one, more, or all of them together, and you can easily tweak this using the global configuration.

By default, our SaaS Starter uses Email/Password and Google Auth.

How does Authentication work?

First, let's just take a high-level overview of how Makerkit's authentication works.

MakerKit uses SSR throughout the application, except for the marketing pages. Using SSR, we can persist the user's authentication on every page and access the user's object on the server before rendering the page.

This can help you both in terms of UX and DX. In fact, persisting the user's session server-side can help you in various scenarios:

  • Simplifying the business logic: for example, checking server-side if a user can access a specific page before rendering that page
  • Rendering the user's data server-side by fetching some data from Firestore in the getServerSideProps function

How does SSR work?

To enable SSR with Firebase Auth, we use Session Cookies.

  1. First, we use the Firebase Auth Client SDK to sign users in, as described in every tutorial. Furthermore, when a user signs in or signs up, we retrieve the ID Token and make a request to our API to create a session cookie. The session cookie remains valid for 14 days, after which it will expire.
  2. The cookie sessionId gets stored as an HTTP-only cookie: we can use this server-side for fetching the current user.
  3. When the token expires, we sign users out of the application

So... how do they work?

  1. The client SDK uses the Firebase Auth credentials stored in the IndexedDB Storage. This includes interacting with Firebase Storage and Firebase Firestore on the client side.
  2. The server-side API uses the sessionId cookie to retrieve and authenticate the current user. We can then use the Firebase Admin API and interact with the various Firebase services.

Authentication Strategies

To add or tweak the authentication strategies of our application, we can update the configuration:

auth: {
  // Enable MFA. You must upgrade to GCP Identity Platform to use it.
  // see: https://cloud.google.com/identity-platform/docs/product-comparison
  enableMultiFactorAuth: false,
  // NB: Enable the providers below in the Firebase Console
  // in your production project
  providers: {
    emailPassword: true,
    phoneNumber: false,
    emailLink: false,
    oAuth: [GoogleAuthProvider],
  },
},

Above, you can see the default configuration. It should look like the following:

Ok, cool. But what if we wanted to swap emailPassword with emailLink and add Twitter oAuth?

We will do the following:

import { GoogleAuthProvider, TwitterAuthProvider } from 'firebase/auth';

auth: {
  // Enable MFA. You must upgrade to GCP Identity Platform to use it.
  // see: https://cloud.google.com/identity-platform/docs/product-comparison
  enableMultiFactorAuth: false,
  // NB: Enable the providers below in the Firebase Console
  // in your production project
  providers: {
    emailPassword: false, // set this to false
    phoneNumber: false,
    emailLink: true, // set this to true
    oAuth: [GoogleAuthProvider, TwitterAuthProvider],
  },
},

And the result will be similar to the image below:

Custom oAuth providers

Additionally, we can add custom oAuth providers, such as Microsoft and Apple:

class MicrosoftAuthProvider extends OAuthProvider {
  constructor() {
    super('microsoft.com');
  }
}

class AppleAuthProvider extends OAuthProvider {
  constructor() {
    super('apple.com');
  }
}

Then, you will add these classes to the auth.providers.oAuth object of the configuration.

Remember that you will always need to enable the authentication methods you want to use from the Firebase Console once you deploy your application to production

Creating Accounts

Users can be redirected to the Sign Up page to create an account.

Onboarding Flow

After sign-up, users are redirected to the onboarding flow. Here, you can ask users questions, configure their accounts or simply show them around.

By default, Makerkit adds one single step, where it asks users to create an organization.

Of course, you can extend it and add as many steps as you wish.

After the user submits the form, the API will receive the request and:

  1. create the user Firestore record at /users
  2. create the organization Firestore record at /organizations and assign the user as its owner

I encourage you to visit the Firestore Emulator UI and see the data created.

What is an "Organization"?

Organizations are groups of users.

You can call them projects, teams, classrooms, or whatever feels suitable for your domain. But, generally speaking, organizations are the backbone of the data model because it's where we store most of the data shared among users.

Users can:

  1. create new Organizations
  2. be invited to other Organizations
  3. switch between organizations using a dropdown

Developing your SaaS

It's time to work on our application's value proposition: adding and tracking tasks! This is likely the most exciting part for you because it's where you get to change things and add your SaaS features to the template.

PRoutingage Structure

Before getting started, let's take a look at the default page structure of the boilerplate is the following.

├── routes
  └── root.tsx
  └── auth.tsx
  └── invite.tsx

  └── __app.tsx
  └── __site.tsx

  └── onboarding
      └── index.tsx

  __site
    └── auth.tsx
      └── faq.tsx
      └── pricing.tsx
  
  └── __auth
    └── link.tsx
    └── password-reset.tsx
    └── sign-in.tsx
    └── sign-up.tsx

  └── invite
    └── $code.tsx

  └── __app
    └── dashboard
      └── index.tsx

    └── settings
      └── organization
        └── members
          └── index.tsx
          └── invite.tsx

      └── profile
        └── index.tsx
        └── email.tsx
        └── password.tsx
        └── authentication.tsx

      └── subscription

  └── index.tsx

The routes are split in the following way:

  1. The website's pages are placed under __site
  2. The auth pages are placed under __auth
  3. The internal pages (behind auth) pages are placed under __app

Some pages in the "middle" are placed outside __app, such as the Invites page and the Onboarding flow. These require custom handling.

Setting the application's Home Page

By default, the application's home page is /dashboard; every time the user logs in, they're redirected to the page src/routes/__app/dashboard/index.tsx.

You can update the above by setting the application's home page path at configuration.paths.appHome.

Routing

Ok, so we want to add three pages to our application:

  1. List: A page to list all our tasks
  2. New Task: Another page to create a new task
  3. Task: A page specific to the selected task

To create these two pages, we will create a folder named tasks at src/routes/__app/tasks.

In the folder src/routes/__app/tasks we will create three Page Components:

  1. List Page: we create a page index.tsx, which is accessible at the path /tasks
  2. New Task Page: we create a page new.tsx, which is accessible at the path /tasks/new
  3. Task Page: we create a page $id.tsx, which is accessible at the path /tasks/<taskID> where taskID is a dynamic variable that refers to the actual ID of the task
├── routes
  └──__app
    └── tasks
    └── index.tsx
    └── new.tsx
    └── $id.tsx

Adding Functionalities to your application

To add new functionalities to your application (in our case, tasks management), usually, you'd need the following things:

  1. Add a new page, and the links to it
  2. Add the components of the domain and import them into the pages
  3. Add data-fetching and writing to this domain's entities

The above are the things we will do in the following few sections. To clarify further the conventions of this boilerplate, here is what you should know:

  1. First, we want to define our data model
  2. Once we're happy with the data model, we can create our Firestore hooks to write new tasks and then fetch the ones we created
  3. Then, we import and use our hooks within the components
  4. Finally, we add the components to the pages

The Makerkit application offers two different layouts: a sidebar layout and a top-header layout. These are two popular layouts for SaaS applications, and it's up to you to choose the one that better fits your application. By default, we use the sidebar layout.

Depending on which layout you choose, you have to update two different navigation menus:

Updating the Sidebar Navigation

If you choose the Sidebar Navigation, you need to open the file AppSidebar.tsx and update the menu in the component AppSidebarMenu.

To add a new link to the sidebar menu, we can do the following (in addition to the other links):


import {
  RectangleStackIcon,
} from '@heroicons/react/24/outline';

<AppSidebarItem href={'/tasks'}>
  <RectangleStackIcon className={'h-6'} />

  <span>
    Tasks
  </span>
</AppSidebarItem>

The result will be similar to the image below:

Updating the Top header Navigation

If you choose the Top Header Navigation, you need to open the file AppNavigation.tsx.

To add a new link to the header menu, we can do the following:

const links = {
  Dashboard: {
    path: '/dashboard',
    i18n: 'common:dashboardTabLabel',
  },
  Settings: {
    path: '/settings',
    i18n: 'common:settingsTabLabel',
  },
  Tasks: {
    path: '/tasks',
    label: 'Tasks',
  },
};

const AppNavigation: React.FCC = () => {
  return (
    <NavigationContainer>
      <NavigationMenu bordered>
        <NavigationItem link={links.Dashboard} />
        <NavigationItem link={links.Tasks} />
        <NavigationItem link={links.Settings} />
      </NavigationMenu>
    </NavigationContainer>
  );
};

The result will be similar to the image below:

Fetching data from Firestore

Before writing the Components, we want to tackle the task of fetching data from Firestore. This involves a couple of steps:

  1. We need to define, on paper, what the data model of the Firestore collections looks like
  2. We need to update the Firestore rules so we can read and write data to the collection
  3. We need to write the hooks to fetch data from Firebase Firestore

Firestore Data Model

First, let's write the data model. But... what does it mean?

When thinking about the Firestore data model, we need to answer the following questions:

  1. Where does the data live?
  2. How is the data structured?
  3. How do we protect the data with security rules?

Ok, let's reply to these questions.

Where does the data live?

We can place tasks as a Firestore top-level collection. Because tasks belong to an organization, we can ensure that only users of that organization can read and write those tasks by adding a foreign key to each task named organizationId.

How is the data structured?

We can define a Task model at src/lib/tasks/types/task.ts:

export interface Task {
  name: string;
  organizationId: string;
  dueDate: string;
  done: boolean;
}
How do we protect the data with security rules?

To write our Security Rules, we will update the file firestore.rules:

match /tasks/{taskId} {
  allow create: if userIsMemberByOrganizationId(incomingData().organizationId);
  allow read, update, delete: if userIsMemberByOrganizationId(existingData().organizationId);
}

The function userIsMemberByOrganizationId is pre-defined in the Makerkit's template: basically, it will verify that the current user is a member of the organization with ID organizationId.

Data Fetching: React Hooks to read data from Firestore

Now that our security rules are updated, we can write Hooks to read data from Firestore.

I recommend writing your entities' hooks at src/lib/tasks/hooks. Let's start with a React Hook to fetch all the organization's tasks:

import { useFirestore, useFirestoreCollectionData } from 'reactfire';

import {
  collection,
  CollectionReference,
  query,
  where,
} from 'firebase/firestore';

import { Task } from '~/lib/tasks/types/task';

function useFetchTasks(organizationId: string) {
  const firestore = useFirestore();
  const tasksCollection = 'tasks';

  const collectionRef = collection(
    firestore,
    tasksCollection
  ) as CollectionReference<WithId<Task>>;

  const path = `organizationId`;
  const operator = '==';
  const constraint = where(path, operator, organizationId);
  const organizationsQuery = query(collectionRef, constraint);

  return useFirestoreCollectionData(organizationsQuery, {
    idField: 'id',
  });
}

export default useFetchTasks;

Let's take a deep breath and slowly go through the above hook.

  1. The hook above uses useFirestoreCollectionData, a React hook from the library reactfire to fetch real-time collection data from Firestore
  2. We build a query that checks that the organizationId parameter matches the organizationId property of each task
  3. Finally, we add { idField: 'id' }. This special parameter decorates the data with the ID of the document. Thanks to the interface WithId, we add an id property to the Task interface returned from Firestore

Displaying Firestore data in Components

Now that we can fetch our data using the hook useFetchTasks, we can build a component that lists each Task.

To do so, let's create a new component named TasksListContainer:

import PageLoadingIndicator from '~/core/ui/PageLoadingIndicator';
import Alert from '~/core/ui/Alert';
import Heading from '~/core/ui/Heading';
import Button from '~/core/ui/Button';

import useFetchTasks from '~/lib/tasks/hooks/use-fetch-tasks';
import TasksList from '~/components/tasks/TasksList';
import { Task } from '~/lib/tasks/types/task';

const TasksContainer: React.FC<{
  organizationId: string;
}> = ({ organizationId }) => {
  const { status, data: tasks } = useFetchTasks(organizationId);

  if (status === `loading`) {
    return <PageLoadingIndicator>Loading Tasks...</PageLoadingIndicator>;
  }

  if (status === `error`) {
    return (
      <Alert type={'error'}>
        Sorry, we encountered an error while fetching your tasks.
      </Alert>
    );
  }

  if (tasks.length === 0) {
    return <TasksEmptyState />;
  }

  return (
    <div className={'flex flex-col space-y-4'}>
      <div className={'mt-2 flex justify-end'}>
        <CreateTaskButton>New Task</CreateTaskButton>
      </div>

      <div className={'flex flex-col space-y-4'}>
        {tasks.map((task) => {
          return <TaskListItem task={task} key={task.id} />;
        })}
      </div>
    </div>
  );
};

function TasksEmptyState() {
  return (
    <div
      className={
        'flex flex-col items-center justify-center space-y-4 h-full p-24'
      }
    >
      <div>
        <Heading type={5}>No tasks found</Heading>
      </div>

      <CreateTaskButton>Create your first Task</CreateTaskButton>
    </div>
  );
}

function TasksList({ tasks }: React.PropsWithChildren<{
  tasks: Task[]
}>) {
  return (
    <div className={'flex flex-col space-y-4'}>
      {tasks.map((task) => {
        return <TaskListItem task={task} key={task.id} />;
      })}
    </div>
  );
}

export default TasksList;


function CreateTaskButton(props: React.PropsWithChildren) {
  return <Button href={'/tasks/new'}>{props.children}</Button>;
}

export default TasksContainer;

The data above will automatically update when the tasks collection changes!

Since the component "TaskLiskItem" is pretty complex and requires more files, we will define it separately. You will find it below after we explain the mutation hooks that the component will use.

Mutations: React Hooks to write data to Firestore

While reactfire does not provide hooks for writing data to Firestore, we can still make our own.

In fact, I encourage you to make a custom hook for each mutation.

Creating a Task

In the example below, we write a custom hook to add a document to the tasks collection:

import { useFirestore } from 'reactfire';
import { useCallback } from 'react';
import { addDoc, collection } from 'firebase/firestore';
import { Task } from '~/lib/tasks/types/task';

function useCreateTask() {
  const firestore = useFirestore();
  const tasksCollection = collection(firestore, `/tasks`);

  return useCallback(
    (task: Task) => {
      return addDoc(tasksCollection, task);
    },
    [tasksCollection]
  );
}

export default useCreateTask;

The hook above returns a callback. Let's take a quick look at its usage:

import useCreateTask from '~/lib/tasks/hooks/use-create-task';

function Component() {
  const createTask = useCreateTask();

  return <Form onCreate={task => createTask(task)} />
}

Updating a Task

Now, let's write a hook to update an existing task.

To update Firestore documents, we will import the function updateDoc from Firestore.

import { useCallback } from 'react';
import { useFirestore } from 'reactfire';
import { doc, updateDoc } from 'firebase/firestore';
import { Task } from '~/lib/tasks/types/task';

function useUpdateTask(taskId: string) {
  const firestore = useFirestore();
  const tasksCollection = 'tasks';

  const docRef = doc(firestore, tasksCollection, taskId);

  return useCallback(
    (task: Partial<Task>) => {
      return updateDoc(docRef, task);
    },
    [docRef]
  );
}

export default useUpdateTask;

Deleting a Task

Finally, we write a mutation to delete a task:

import { useFirestore } from 'reactfire';
import { deleteDoc, doc } from 'firebase/firestore';
import { useCallback } from 'react';

function useDeleteTask(taskId: string) {
  const firestore = useFirestore();
  const collection = `tasks`;
  const task = doc(firestore, collection, taskId);

  return useCallback(() => {
    return deleteDoc(task);
  }, [task]);
}

export default useDeleteTask;

Using the Modal component for confirming actions

The Modal component is excellent for asking for confirmation before performing a destructive action. In our case, we want the users to confirm before deleting a task.

The ConfirmDeleteTaskModal is defined below using the core Modal component:

import Modal from '~/core/ui/Modal';
import Button from '~/core/ui/Button';

const ConfirmDeleteTaskModal: React.FC<{
  isOpen: boolean;
  setIsOpen: (isOpen: boolean) => void;
  task: string;
  onConfirm: () => void;
}> = ({ isOpen, setIsOpen, onConfirm, task }) => {
  return (
    <Modal heading={`Deleting Task`} isOpen={isOpen} setIsOpen={setIsOpen}>
      <div className={'flex flex-col space-y-4'}>
        <p>
          You are about to delete the task <b>{task}</b>
        </p>

        <p>Do you want to continue?</p>

        <Button block color={'danger'} onClick={onConfirm}>
          Yep, delete task
        </Button>
      </div>
    </Modal>
  );
};

export default ConfirmDeleteTaskModal;

Wrapping all up: listing each Task Item

Now that we have defined the mutations we can perform on each task item, we can wrap it up.

The component below represents a task item and allows users to mark it as done or not done - or delete them.

import { useCallback, useState } from 'react';
import Link from 'next/link';
import { TrashIcon } from '@heroicons/react/24/outline';
import toaster from 'react-hot-toast';
import { formatDistance } from 'date-fns';

import { Task } from '~/lib/tasks/types/task';
import Heading from '~/core/ui/Heading';
import IconButton from '~/core/ui/IconButton';
import Tooltip from '~/core/ui/Tooltip';
import useDeleteTask from '~/lib/tasks/hooks/use-delete-task';
import ConfirmDeleteTaskModal from '~/components/tasks/ConfirmDeleteTaskModal';
import useUpdateTask from '~/lib/tasks/hooks/use-update-task';

const TaskListItem: React.FC<{
  task: WithId<Task>;
}> = ({ task }) => {
  const getTimeAgo = useTimeAgo();
  const deleteTask = useDeleteTask(task.id);
  const updateTask = useUpdateTask(task.id);

  const [isDeleting, setIsDeleting] = useState(false);

  const onDelete = useCallback(() => {
    const deleteTaskPromise = deleteTask();

    return toaster.promise(deleteTaskPromise, {
      success: `Task deleted!`,
      loading: `Deleting task...`,
      error: `Ops, error! We could not delete task`,
    });
  }, [deleteTask]);

  const onDoneChange = useCallback(
    (done: boolean) => {
      const promise = updateTask({ done });

      return toaster.promise(promise, {
        success: `Task updated!`,
        loading: `Updating task...`,
        error: `Ops, error! We could not update task`,
      });
    },
    [updateTask]
  );

  return (
    <>
      <div
        className={'rounded border p-4 transition-colors dark:border-black-400'}
      >
        <div className={'flex items-center space-x-4'}>
          <div>
            <Tooltip content={task.done ? `Mark as not done` : `Mark as done`}>
              <input
                className={'Toggle cursor-pointer'}
                type="checkbox"
                defaultChecked={task.done}
                onChange={(e) => {
                  return onDoneChange(e.currentTarget.checked);
                }}
              />
            </Tooltip>
          </div>

          <div className={'flex flex-1 flex-col space-y-0.5'}>
            <Heading type={5}>
              <Link
                className={'hover:underline'}
                href={`/tasks/[id]`}
                as={`/tasks/${task.id}`}
                passHref
              >
                {task.name}
              </Link>
            </Heading>

            <div>
              <p className={'text-xs text-gray-400 dark:text-gray-500'}>
                Due {getTimeAgo(new Date(task.dueDate))}
              </p>
            </div>
          </div>

          <div className={'flex justify-end'}>
            <Tooltip content={`Delete Task`}>
              <IconButton
                onClick={(e) => {
                  e.stopPropagation();
                  setIsDeleting(true);
                }}
              >
                <TrashIcon className={'h-5 text-red-500'} />
              </IconButton>
            </Tooltip>
          </div>
        </div>
      </div>

      <ConfirmDeleteTaskModal
        isOpen={isDeleting}
        setIsOpen={setIsDeleting}
        task={task.name}
        onConfirm={onDelete}
      />
    </>
  );
};

export default TaskListItem;

function useTimeAgo() {
  return useCallback((date: Date) => {
    return formatDistance(date, new Date(), {
      addSuffix: true,
    });
  }, []);
}

Form Submission

Now that we have created a custom hook to write data to Firestore, we need to build a form to create a new task.

The example below is straightforward:

  1. We have a form with two input fields
  2. When the form is submitted, we read the data using FormData
  3. Finally, we add the document using the callback returned by the hook useCreateTask
import { useRouter } from 'next/router';
import { FormEventHandler, useCallback } from 'react';

import TextField from '~/core/ui/TextField';
import Button from '~/core/ui/Button';
import useCreateTask from '~/lib/tasks/hooks/use-create-task';

import { useCurrentOrganization } from '~/lib/organizations/hooks/use-current-organization';

const CreateTaskForm = () => {
  const createTask = useCreateTask();
  const router = useRouter();
  const organization = useCurrentOrganization();
  const organizationId = organization?.id as string;

  const onCreateTask: FormEventHandler<HTMLFormElement> = useCallback(
    async (event) => {
      event.preventDefault();

      const target = event.currentTarget;
      const data = new FormData(target);
      const name = data.get('name') as string;
      const dueDate = data.get('dueDate') as string;

      const task = {
        organizationId,
        name,
        dueDate,
        done: false,
      };

      // create task
      await createTask(task);

      // redirect to /tasks
      await router.push(`/tasks`);
    },
    [router, createTask, organizationId, setLoading]
  );

  return (
    <form onSubmit={onCreateTask}>
      <div>
        <TextField.Label>
          Name
          <TextField.Input
            required
            name={'name'}
            placeholder={'ex. Launch on IndieHackers'}
          />

          <TextField.Hint>Hint: whatever you do, ship!</TextField.Hint>
        </TextField.Label>

        <TextField.Label>
          Due date
          <TextField.Input required name={'dueDate'} type={'date'} />
        </TextField.Label>

        <div>
          <Button>
            Create Task
          </Button>
        </div>
      </div>
    </form>
  );
};

export default CreateTaskForm;

Writing Application Pages

Now that we have some components to display, we need to add them to the actual Remix pages.

If you have not created the files in the Routing section above, it's time to do it.

Using the RouteShell component

The RouteShell component is a wrapper around your internal application pages. This component will:

  1. Automatically protect pages when the user is not authenticated
  2. Initializes the Firestore provider on the page
import RouteShell from `~/components/RouteShell`;

function MyPage() {
  return (
    <RouteShell title="Tasks">
      Your Page goes here
    </RouteShell>
  )
}

API Routes

Makerkit provides some utilities to reduce the boilerplate needed to write Remix API functions. This section will teach you everything you need to know to write your API functions.

Calling API functions from the client

To make requests to the API functions in the api folder, we provide a custom hook useApiRequest, a wrapper around fetch.

It has the following functionality:

  1. Uses an internal state to keep track of the state of the request, like loading, error and success. This helps you write fetch requests the "hooks way"
  2. Automatically adds a Firebase AppCheck Token to the request headers if you enabled Firebase AppCheck
  3. Automatically adds a CSRF token to the request headers

Similarly to making Firestore Requests, it's a convention to create a custom hook for each request for readability/reusability reasons.

import { useApiRequest } from '~/core/hooks/use-api';

interface Body {
  idToken: string;
}

export function useCreateSession() {
  return useApiRequest<void, Body>('/api/session/sign-in');
}

The hook returns an array:

  1. Callback: the first element is the callback to make the request
  2. State: the second element is the state object of the request
const [createSession, createSessionState] = useCreateSession();

The state object internally uses useApiRequest, and has the following interface:

{
  success: boolean;
  loading: boolean;
  error: string;
  data: T | undefined;
}

When success is true, the property data is inferred with its correct type.

You can use this hook in your components:

import { useCreateSession } from '~/core/hooks/use-create-session';

function Component() {
  const [createSession, createSessionState] = useCreateSession();

  return (
    <>
      { createSessionState.loading ? `Loading...` : null }
      { createSessionState.error ? `Error :(` : null }
      { createSessionState.success ? `Yay, success!` : null }

      <SignInForm onSignIn={(idToken) => createSession({ idToken })} />
    </>
  );
}

Similarly, you can also use it to fetch data:

import { useCreateSession } from '~/core/hooks/use-create-session';

function Component() {
  const [fetchMembers, { loading, error, data }]
    = useFetchMembers();

  // fetch data when the component mounts
  useEffect(() => {
    fetchMembers();
  }, [fetchMembers]);

  if (loading) {
    return <div>Fetching members...</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div>
      {data.map(member => <MemberItem member={member} />)}
    </div>
  );
}

Writing your own Fetch Hook

You are free to use your own implementation for sending HTTP requests to your API or use a powerful third-party library.

With that said, you need to ensure that you're sending the required headers:

  1. The AppCheck token (if you use Firebase AppCheck)
  2. The CSRF Token (for POST requests)
Generating an App Check Token

To generate an App Check token, you can use the useGetAppCheckToken hook:

const getAppCheckToken = useGetAppCheckToken();
const appCheckToken = await getAppCheckToken();

console.log(appCheckToken) // token

You will need to send a header X-Firebase-AppCheck with the resolved value returned by the promise getAppCheckToken().

Sending the CSRF Token

To retrieve the page's CSRF token, you can use the useGetCsrfToken hook:

const getCsrfToken = useGetCsrfToken();
const csrfToken = getCsrfToken();

console.log(csrfToken) // token

You will need to send a header x-csrf-token with the value returned by getCsrfToken().

CSRF Token check

We must pass a CSRF token when using POST requests to prevent malicious attacks. To do so, we use the pipe withCsrfToken.

  1. The CSRF token is generated when the page is server-rendered
  2. The CSRF token is stored in a meta tag
  3. The CSRF token is sent to an HTTP POST request automatically when using the useApiRequest hook
  4. This function will throw an error when the token is invalid

By using this function, we ensure all the following functions will not be executed unless the token is valid.

export const action: ActionFunction = async ({ request }) => {
  await withCsrf(request);
}

Firebase App Check

App Check is a Firebase service that helps you to protect your web app from bots, spammy users, and general abuse detected by Google's Recaptcha.

Check out the documentation to setup Firebase App Check.

Using the withAppCheck pipe, we ensure all the following functions will not be executed unless the App Check token is valid.

export const action: ActionFunction = async ({ request }) => {
  await withAppCheck(request);
}

API Payload Validation

Validating payloads is necessary to ensure your API endpoints receive the expected data. To validate the API, we use Zod.

Zod is a Typescript library that helps us secure our API endpoints by validating the payloads sent from the client and also facilitating the typing of the payload with Typescript.

Using Zod is the first line of defense to validate the data sent against our API: as a result, it's something we recommend you keep doing. It ensures we write safe, resilient, and valid code.

When we write an API endpoint, we first define the schema of the payload:

function getBodySchema() {
  return z.object({
    displayName: z.string(),
    email: z.string().email(),
  });
}

This function represents the schema, which will validate the following interface:

interface Body {
  displayName: string;
  email: Email;
}

Now, let's write the body of the API handler that validates the body of the function, which we expect to be equal to the Body interface.

import { throwBadRequestException } from `~/core/http-exceptions`;

export const action: ActionFunction = async ({ request }) => {
  try {
     // we can safely use data with the interface Body
    const schema = getBodySchema();
    const body = await request.json();
    const { displayName, email } = schema.parse(body);

    return sendInvite({ displayName, email });
  } catch(e) {
    return throwBadRequestException();
  }
}

I encourage you to never skip the validation step when writing your API endpoints.

Catching and Handling Exceptions

To catch and gracefully handle API exceptions, we use the function withExceptionFilter.

As seen from its usage above, we wrap the API function within the utility. When errors are caught, this function will:

  1. Log and debug the error to the console
  2. Report the error to Sentry (if configured)
  3. Return an object stripping the error's data to avoid leaking information

API Logging

The boilerplate uses Pino for API logging, a lightweight logging utility for Node.js.

Logging is necessary to debug your applications and understand what happens when things don't behave as expected. You will find various instances of logging throughout the API, but we encourage you to log more if necessary.

We import the logging utility from ~/core/logger. Typically, you can log every time you perform an action, both before and after. For example:

async function myFunction(params: {
  organizationId: string;
  userId: string;
}) {
  logger.info(
    {
      organizationId: params.organizationId,
      userId: params.userId,
    },
    `Performing action...`
  );

  await performAction();

  logger.info(
    {
      organizationId: params.organizationId,
      userId: params.userId,
    },
    `Action successful`
  );
}

It's always important to add context to your logs: as you can see, we use the first parameter to add important information.

Translating the Remix application into multiple languages

Most strings in the Makerkit template's application use remix-i18next, a library to translate your application into multiple languages. Thanks to this library, we can store all the application's text in json files for each supported language.

For example, if you are serving your application in English and Spanish, you'd have the following files:

  • English translation files at /public/locales/en/{file}.json
  • Spanish translation files at /public/locales/es/{file}.json

There are valid reasons to use translation files, even if you are not planning on translating your application, such as:

  1. it's easier to search and replace text
  2. tidier render functions
  3. easy update path if you do decide to support a new language

Adding new languages

By default, Makerkit uses English for translating the website's text. All the files are stored in the files at /public/locales/en.

Adding a new language is very simple:

  1. Translation Files: First, we need to create a new folder, such as /public/locales/es, and then copy over the files from the English version and start translating files.
  2. Remix i18n config: We need to also add a new language to the Remix configuration at app/i18n/i18next.config.ts. Simply add your new language's code to the supportedLanguages array.

The configuration will look like the below:

const i18Config = {
  fallbackLanguage: DEFAULT_LOCALE,
  supportedLanguages: [DEFAULT_LOCALE, 'es'],
  defaultNS: ['common', 'auth', 'organization', 'profile', 'subscription'],
  react: { useSuspense: false },
};

Setting the default Locale

To set the default locale, simply update the environment variable DEFAULT_LOCALE stored in .env.

So, open the .env file, and update the variable:

DEFAULT_LOCALE=de

Using the Language Switcher component

The Language switcher component will automatically retrieve and translate the languages listed in your configuration.

When the user changes language, it will update the URL to reflect the user's preferences and rerender the application with the selected language.

Loading video...

NB: The language selector is not added to the application by default; you will need to import it where you want to place it.

Updating the Marketing Website

Adding pages to the Navigation Menu

To update the site's navigation menu, you can visit the SiteNavigation.tsx component and add a new entry to the menu.

By default, you will see the following object links:

const links: Record<string, Link> = {
  Blog: {
    label: 'Blog',
    path: '/blog',
  },
  Docs: {
    label: 'Docs',
    path: '/docs',
  },
  Pricing: {
    label: 'Pricing',
    path: '/pricing',
  },
  FAQ: {
    label: 'FAQ',
    path: '/faq',
  },
};

The menu is defined in the render function:

<NavigationMenu>
  <NavigationMenuItem link={links.Blog} />
  <NavigationMenuItem link={links.Docs} />
  <NavigationMenuItem link={links.Pricing} />
  <NavigationMenuItem link={links.FAQ} />
</NavigationMenu>

Assuming we want to add a new menu entry, say About, we would first add the link object:

About: {
  label: 'About',
  path: '/about',
},

And then we update the menu:

<NavigationMenu>
  <NavigationMenuItem link={links.About} />
  ...
</NavigationMenu>

Going to Production

Before going to Production, ensure to follow the [production checklist] (/docs/remix-fire/going-to-production-overview) below:

  1. Setting up your Firebase Project
  2. Enabling the Authentication Providers
  3. Syncing your Security Rules
  4. Adding Firestore Indexes. Additionally, ensure your complex queries do not need additional indexes, as the Emulator will not reject those requests.
  5. Setting up an Email Provider. Remember to update the configuration.email object with your Email provider's details and credentials.

Updating your Project

If you have followed the steps to set up Git at the beginning of this tutorial, you've already set the original Makerkit repository as upstream.

As the repository is constantly updated, it's recommended to fetch updates regularly. You can do so by running the following Git command:

git pull upstream main --allow-unrelated-histories

Unfortunately, you may need to resolve eventual conflicts.

Any questions?

If you have questions, please join our Discord Community, even if you have not purchased any kit. We chat and help each other build products.


Stay informed with our latest resources for building a SaaS

Subscribe to our newsletter to receive updatesor