Build a Serverless React App with Vercel and FaunaDB
Introduction
Serverless architecture is becoming increasingly popular due to its scalability and cost-effectiveness. This article guides you through building a simple React application, deploying it on Vercel, and connecting it to FaunaDB.
Prerequisites
- Node.js and npm installed
- A Vercel account
- A FaunaDB account
Setting up the React App
First, create a new React application using Create React App:
npx create-react-app my-serverless-app
cd my-serverless-app
Integrating FaunaDB
Install the FaunaDB JavaScript driver:
npm install faunadb
Create a .env
file at the root of your project and add your FaunaDB secret key:
FAUNADB_SECRET=<YOUR_FAUNADB_SECRET>
Important: Never commit your .env
file to version control.
Now, create a file named fauna.js
in the src
directory to initialize the FaunaDB client:
// src/fauna.js
import faunadb from 'faunadb';
const q = faunadb.query;
const client = new faunadb.Client({
secret: process.env.REACT_APP_FAUNADB_SECRET,
});
export { client, q };
Note: For the React app to read environment variables, you need to prefix it with REACT_APP_
. Remember to rename FAUNADB_SECRET
in your .env
file to REACT_APP_FAUNADB_SECRET
.
Creating a Simple Component
Let's create a simple component that fetches data from FaunaDB. First, create a collection in FaunaDB named "todos." Then create an index named "all_todos".
// src/components/Todo.js
import React, { useState, useEffect } from 'react';
import { client, q } from '../fauna';
function Todo() {
const [todos, setTodos] = useState([]);
useEffect(() => {
const fetchTodos = async () => {
try {
const result = await client.query(
q.Map(
q.Paginate(q.Match(q.Index("all_todos"))),
q.Lambda("X", q.Get(q.Var("X")))
)
);
setTodos(result.data.map(todo => ({ id: todo.ref.id, ...todo.data })));
} catch (error) {
console.error('Error fetching todos:', error);
}
};
fetchTodos();
}, []);
return (
<div>
<h2>Todos</h2>
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</div>
);
}
export default Todo;
Modify your App.js
to include the Todo Component
import React from 'react';
import Todo from './components/Todo';
function App() {
return (
<div className="App">
<Todo />
</div>
);
}
export default App;
Remember to add a text
field to your todo items when creating them in FaunaDB for the above component to render correctly.
Deploying to Vercel
- Commit your code to a Git repository (e.g., GitHub).
- Create a Vercel project and connect it to your Git repository.
- Add the
REACT_APP_FAUNADB_SECRET
environment variable to your Vercel project settings.
Vercel will automatically deploy your application whenever you push changes to your Git repository.
Conclusion
You have successfully built and deployed a serverless React application using Vercel and FaunaDB. This provides a solid foundation for building more complex serverless applications.