Bootstraping the Frontend with Next.js

Bootstrapping the Frontend with Next.js

With our backend deployed on Keel and our API endpoints ready, we can now build our front end.

First, we need to scaffold a Next.js application interactively with the create-next-app CLI tool by running the following command

npx create-next-app@latest

Make sure to select TypeScript and app router for routing as extra options while going through the interactive install.

After the application has been created, please run the following command to start the Next.js development server

npm run dev

With the base setup for our application now in place, let’s set up the Keel client.

Remember the Keel client we generated earlier? Copy that file and in the src folder of our frontend application, create a utils folder and paste the file in it. We’ll need this file to interact with our Keel API.

Setup Keel React Client

For handling context in React, we have created a package (opens in a new tab) for generating a typed useKeel Hook based on your Keel client.

To set this up in our project, we need to first install it by running the following command:

npm i @teamkeel/client-react

The above command will install the Keel client react package as a dependency in our application.

Since we are using the Next.js 13 app router (opens in a new tab) for routing in our application and server components do not support context (opens in a new tab), we can use this package by creating a keelcontext.ts file in the utils folder we created earlier and pasting the following configuration options for the Keel client react package we installed.

import { keel } from '@teamkeel/client-react';
import { APIClient } from './keelClient';
export const { KeelProvider, useKeel } = keel(APIClient);

With this setup, we can now make use of the useKeel hook and KeelProvider in our application.

The next thing we need to do is to make the following additions to our layout.tsx file and initialize our Keel provider like so:

'use client'
// import the Keel Provider
import { KeelProvider } from '@/utils/keelContext'
// existing code
export default function RootLayout({
}: {
  children: React.ReactNode
}) {
  return (
		// initialize keel provider
    <KeelProvider baseUrl=''>
    <html lang="en">
      <body className={inter.className}>{children}</body>

This code has been truncated to reduce repeated code, read the code comments to know the new additions to the previous code.

Make sure the content of the baseUrl attribute matches the API endpoint generated in the Keel console.

We've successfully set up our Keel client and API endpoint in our Next.js application.

Now, we can conveniently utilize our API endpoints throughout the application as needed.