owned this note
owned this note
Published
Linked with GitHub
# Building a Google Meet Clone with Strapi 5 and Next.js - Part 2
Welcome back to our Google Meet clone tutorial series! In Part 1, we learned how to set up a Strapi 5 project, create Content Types, create data Relationships, and create custom controllers and routes in Strapi.
For reference purposes, here's the outline of this blog series:
- Part 1: [Setting Up the Backend with Strapi 5](https://).
- Part 2: [Building the Frontend with Next.js](https://).
- Part 3: [Real-Time Features, Video Integration, and Screen Sharing](https://).
In Part 2, we'll build a responsive frontend using Next.js, create the user interfaces, implement authentication, and handle meeting listing and creating new meetings.
## Project Setup
Let's create a new Next.js project with TypeScript and Tailwind CSS:
```bash
px create-next-app@latest google-meet-frontend --typescript --tailwind --app
cd google-meet-frontend
```
Then, install the required project dependencies:
```bash
npm install @tanstack/react-query axios jwt-decode @headlessui/react lucide-react clsx tailwind-merge zustand @types/js-cookie js-cookie
```
Here is a brief overview of the dependencies and what they will do:
- **@tanstack/react-query**: Manages API data fetching, caching, and synchronization
- **axios**: Makes HTTP requests to our backend
- **jwt-decode**: Decodes JWT tokens for authentication
- **@headlessui/react**: Provides unstyled, accessible UI components
- **lucide-react**: Modern icon library for React
- **clsx**: Helps build className strings conditionally
- **tailwind-merge**: Merges Tailwind CSS classes without conflicts.
- **zustand**: Simple state management solution
### Project Structure
Once the project is created and the required dependencies is installed, let's organize our project structure:
```bash
📦google-meet-frontend
┣ 📂app
┃ ┣ 📂auth
┃ ┃ ┣ 📂login
┃ ┃ ┃ ┗ 📜page.tsx
┃ ┃ ┣ 📂register
┃ ┃ ┃ ┗ 📜page.tsx
┃ ┃ ┗ 📜layout.tsx
┃ ┣ 📂meetings
┃ ┃ ┣ 📂[id]
┃ ┃ ┃ ┗ 📜page.tsx
┃ ┃ ┣ 📂new
┃ ┃ ┃ ┗ 📜page.tsx
┃ ┃ ┗ 📜page.tsx
┃ ┣ 📜layout.tsx
┃ ┗ 📜page.tsx
┣ 📂components
┃ ┣ 📂meeting
┃ ┃ ┣ 📜chat.tsx
┃ ┃ ┣ 📜controls.tsx
┃ ┃ ┗ 📜participant-list.tsx
┃ ┣ 📜header.tsx
┃ ┗ 📜providers.tsx
┣ 📂lib
┃ ┣ 📜api-client.ts
┃ ┗ 📜cookie-manager.ts
┣ 📂store
┃ ┣ 📜auth-store.ts
┃ ┗ 📜meeting-store.ts
┣ 📂types
┃ ┗ 📜index.ts
┣ 📜.env.local
┣ 📜middleware.ts
```
Then create a `.env.local` file in your project root and add the following environment variables:
```bash
NEXT_PUBLIC_STRAPI_URL=http://localhost:1337
NEXT_PUBLIC_API_URL=http://localhost:1337/api
```
## Handling Authentication and Authorization
Strapi provides different types of authentication and authorization, for the demonstration in this tutorial, we'll use the **Password-based authentication** and **API Keys** authorization. To learn more about Strapi authentication, check out the Strapi blog on [A Beginner's Guide to Authentication and Authorization in Strapi](https://strapi.io/blog/a-beginners-guide-to-authentication-and-authorization-in-strapi).
### Setting Up User Authentication
Let's create our authentication store using Zustand. Create a `store/auth-store.ts` file and add the code snippets:
```typescript
import { cookieManager } from "@/lib/cookie-manager";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
interface User {
id: number;
email: string;
username: string;
avatar?: string;
}
interface AuthState {
user: User | null;
token: string | null;
isInitialized: boolean;
setAuth: (user: User, token: string) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
token: null,
isInitialized: false,
setAuth: (user, token) => {
set({ user, token, isInitialized: true });
cookieManager.setAuthCookie(user, token);
},
logout: () => {
set({ user: null, token: null, isInitialized: true });
cookieManager.clearAuthCookie();
},
}),
{
name: "auth-storage",
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
user: state.user,
token: state.token,
}),
}
)
);
```
The above code creates an authentication store using Zustand's `create` and `persist` middleware. The `useAuthStore` hook creates a persistent state container with null initial values for the user and token, along with `isInitialized` flag. It exposes two functions: `setAuth` which takes a `User` object and `token` string to update the authentication state and syncing cookies using `cookieManager.setAuthCookie`, and `logout` which nullifies the user and token and clears cookies using `cookieManager.clearAuthCookie`. The `persist` configuration named `auth-storage` uses `localStorage` to persist data.
Then create the cookie manager in the `lib/cookie-manager.ts` to manage users' cookies with the code:
```typescript
import Cookies from "js-cookie";
export const cookieManager = {
setAuthCookie: (user: any, token: string) => {
Cookies.set(
"auth-storage",
JSON.stringify({
state: { user, token },
}),
{
expires: 7,
path: "/",
sameSite: "strict",
}
);
},
clearAuthCookie: () => {
Cookies.remove("auth-storage", { path: "/" });
},
};
```
Now you need to create an API client in `lib/api-client.ts`. It will allow you reuse the pre-configured Axios instance that will handle authentication by automatically adding the JWT token from your Zustand auth store to the request headers. It also uses the base URL from your environment variables for all API calls to Strapi.
```typescript
import axios from 'axios';
import { useAuthStore } from '@/store/auth-store';
const apiClient = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});
apiClient.interceptors.request.use((config) => {
const token = useAuthStore.getState().token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default apiClient;
```
### Creating Login Page
Create a page in `app/auth/login/page.tsx` and add the code snippet for the login page to allow users log in to the application.
```typescript
"use client";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import apiClient from "@/lib/api-client";
import { useAuthStore } from "@/store/auth-store";
export default function LoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const router = useRouter();
const searchParams = useSearchParams();
const redirectUrl = searchParams.get("redirect") || "/meetings";
const setAuth = useAuthStore((state) => state.setAuth);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setError("");
try {
const response = await apiClient.post("/auth/local", {
identifier: email,
password,
});
setAuth(response.data.user, response.data.jwt);
router.push(redirectUrl);
} catch (error: any) {
setError(error.response?.data?.error?.message || "Failed to login");
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full p-6 bg-white rounded-lg shadow-md">
<div className="text-center mb-8">
<h1 className="text-2xl font-bold text-gray-600">Welcome Back</h1>
<p className="text-gray-600">Sign in to your account</p>
</div>
{error && (
<div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700"
>
Email
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-1 block w-full text-gray-700 rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
Password
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 block w-full text-gray-700 rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{isLoading ? "Signing in..." : "Sign In"}
</button>
</form>
<p className="mt-4 text-center text-sm text-gray-600">
Don't have an account?{" "}
<Link
href="/auth/register"
className="text-blue-600 hover:text-blue-700"
>
Sign up
</Link>
</p>
</div>
</div>
);
}
```
The above code will require users to log in with their email and password, and then send a POST request to the Strapi authentication endpoint (`/auth/local`) to log users in. Then on successfully login, it will update the `auth-store` to save the user's access token.
![Login Authentication page](https://hackmd.io/_uploads/SJWqPFPlyl.png)
### Creating the Register Page
Next, create the user registration page in the `app/auth/register/page.tsx` to allow users create an account:
```typescript
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import apiClient from "@/lib/api-client";
import { useAuthStore } from "@/store/auth-store";
export default function RegisterPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [username, setUsername] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const router = useRouter();
const setAuth = useAuthStore((state) => state.setAuth);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setError("");
try {
const response = await apiClient.post("/auth/local/register", {
username: username,
email,
password,
});
setAuth(response.data.user, response.data.jwt);
router.push("/meetings");
} catch (error: any) {
setError(error.response?.data?.error?.message || "Failed to register");
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full p-6 bg-white rounded-lg shadow-md">
<div className="text-center mb-8">
<h1 className="text-2xl font-bold text-gray-600">Create Account</h1>
<p className="text-gray-600">Join us today</p>
</div>
{error && (
<div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="username"
className="block text-sm font-medium text-gray-700"
>
Username
</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="mt-1 block w-full rounded-md border text-gray-700 border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700"
>
Email
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-1 block w-full rounded-md border text-gray-700 border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
Password
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 block w-full rounded-md border text-gray-700 border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{isLoading ? "Creating account..." : "Create Account"}
</button>
</form>
<p className="mt-4 text-center text-sm text-gray-600">
Already have an account?{" "}
<Link
href="/auth/login"
className="text-blue-600 hover:text-blue-700"
>
Sign in
</Link>
</p>
</div>
</div>
);
}
```
The above will require users to register with their `username`, `email`, and `password`. We send a POST request to the Strapi register auth route (/aut/register)Once their account is registered, we update we grab their **API Key** update the `auth-store`, and redirect them to the meetings page.
![Screenshot 2024-10-24 at 09.40.03](https://hackmd.io/_uploads/ry_ZOYPlyl.png)
Now create an `authLayouth` component in the `app/auth/layout.tsx` to render the authentication pages:
```typescript
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return <div className="min-h-screen bg-gray-50">{children}</div>;
}
```
### Protected Route Middleware
Create a middleware to protect routes in `middleware.ts` allowing authenticated users to access the meetings pages:
```typescript
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const authState = request.cookies.get("auth-storage")?.value;
let isAuthenticated = false;
if (authState) {
try {
const parsedAuthState = JSON.parse(authState);
isAuthenticated = !!(
parsedAuthState.state?.token && parsedAuthState.state?.user
);
} catch (error) {
console.error("Error parsing auth state:", error);
}
}
const isAuthPage =
request.nextUrl.pathname.startsWith("/auth/login") ||
request.nextUrl.pathname.startsWith("/auth/register");
if (!isAuthenticated && !isAuthPage) {
const loginUrl = new URL("/auth/login", request.url);
loginUrl.searchParams.set("/auth/redirect", request.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
if (isAuthenticated && isAuthPage) {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/", "/meetings/:path*", "/auth/login", "/auth/register"],
};
```
The above middleware handles authentication routing by checking a cookie named `auth-storage` which contains the user's auth state. The middleware will run before the pages load, verifying if the user is authenticated by looking for a valid token and user object in the parsed cookie. It redirects unauthenticated users to the login page (while preserving their intended destination as a URL parameter).
## Creating Meeting Pages
Now that users can register and login, let's proceed to creating the meeting pages to allow users create new meetings and join and manage meetings.
### Creating Meeting Types
First, create a **Meeting**, **User**, **MeetingParticipant** and **ChatMessage** types in the `types/index.ts` directory with code snippet below:
```typescript
export interface User {
id: number;
email: string;
username: string;
avatar?: string;
}
export interface Meeting {
id: number;
title: string;
meetingId: string;
startTime: string;
endTime: string;
isActive: boolean;
createdAt: string;
updatedAt: string;
host: {
data: {
id: number;
username: string;
email: string;
};
participants: {
data: Array<{
id: number;
username: string;
email: string;
}>;
};
};
}
export interface MeetingParticipant {
id: number;
username: string;
isAudioEnabled: boolean;
isVideoEnabled: boolean;
isScreenSharing: boolean;
}
export interface ChatMessage {
id: string;
userId: number;
text: string;
timestamp: number;
username: string;
}
```
### Creating App Layout Components
Next, create a `Header` component in `components/header.tsx`. This **Header** component will be reused across the meetings pages:
```typescript
'use client';
import Link from 'next/link';
import { useAuthStore } from '@/store/auth-store';
import { LogOut, User } from 'lucide-react';
export function Header() {
const { user, logout } = useAuthStore();
if (!user) return null;
return (
<header className="border-b">
<div className="container mx-auto px-4 h-16 flex items-center justify-between">
<Link href="/meetings" className="font-semibold text-xl">
Meet Clone
</Link>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<User size={20} />
<span>{user.displayName}</span>
</div>
<button
onClick={logout}
className="flex items-center gap-2 text-red-600 hover:text-red-700"
>
<LogOut size={20} />
<span>Logout</span>
</button>
</div>
</div>
</header>
);
}
```
Then create a Providers for the state management using tanstack in the `components/providers.tsx`:
```typescript
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { PropsWithChildren } from 'react';
const queryClient = new QueryClient();
export function Providers({ children }: PropsWithChildren) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}
```
Now update the main app layout component in `app/layout.tsx`:
```typescript
import { Inter } from 'next/font/google';
import { Providers } from '@/components/providers';
import { Header } from '@/components/header';
const inter = Inter({ subsets: ['latin'] });
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<Providers>
<Header />
<main className="container mx-auto px-4 py-8">
{children}
</main>
</Providers>
</body>
</html>
);
}
```
This is what your page will look like now.
![Header section](https://hackmd.io/_uploads/Hk0e59vekg.png)
### Creating a Meeting Page
Create a meeting page in `app/meetings/page.tsx` to display all user's meetings, a button to create new meetings, and a link to join meetings:
```typescript
"use client";
import { useQuery } from "@tanstack/react-query";
import apiClient from "@/lib/api-client";
import Link from "next/link";
import { Meeting } from "@/types";
import { useAuthStore } from "@/store/auth-store";
export default function MeetingList() {
const authState = useAuthStore((state) => state.user);
const { data: meetings, isLoading } = useQuery({
queryKey: ["meetings"],
queryFn: async () => {
const response = await apiClient.get(
`/meetings?filters[participants][id][$eq]=${authState?.id}&populate=*`
);
return response.data.data;
},
});
if (isLoading) {
return <div>Loading meetings...</div>;
}
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
<h2 className="text-2xl font-bold">Your Meetings</h2>
<Link
href="/meetings/new"
className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
>
New Meeting
</Link>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{meetings?.map((meeting: Meeting) => (
<div
key={meeting.id}
className="border rounded-lg p-4 hover:shadow-md transition-shadow"
>
<h3 className="font-semibold">{meeting.title}</h3>
<p className="text-gray-600">
{new Date(meeting.startTime).toLocaleString()}
</p>
<Link
href={`/meetings/${meeting.meetingId}`}
className="text-blue-600 hover:underline mt-2 inline-block"
>
Join Meeting
</Link>
</div>
))}
</div>
</div>
);
}
```
The above code will send a a **GET** request to your Strapi backend to fetch all the meetings that the active your is a participant using the Strapi **filter** query and populate all the relation fields using the **populate** query.
![Meeting page](https://hackmd.io/_uploads/rymhiqwg1l.png)
### Creating a New Meeting
Create a new meeting page in `app/meetings/new/page.tsx` to allow users create meetings and add participants:
```typescript
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { X, Plus, Mail, Loader2 } from "lucide-react";
import apiClient from "@/lib/api-client";
interface FormErrors {
title?: string;
startTime?: string;
endTime?: string;
email?: string;
}
export default function NewMeetingForm() {
const [title, setTitle] = useState("");
const [startTime, setStartTime] = useState("");
const [endTime, setEndTime] = useState("");
const [email, setEmail] = useState("");
const [participantEmails, setParticipantEmails] = useState<string[]>([]);
const [errors, setErrors] = useState<FormErrors>({});
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const validateEmail = (email: string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const addParticipant = () => {
if (!email.trim()) {
setErrors({ ...errors, email: "Email is required" });
return;
}
if (!validateEmail(email)) {
setErrors({ ...errors, email: "Invalid email format" });
return;
}
if (participantEmails.includes(email)) {
setErrors({ ...errors, email: "Email already added" });
return;
}
setParticipantEmails([...participantEmails, email.trim()]);
setEmail("");
setErrors({ ...errors, email: undefined });
};
const removeParticipant = (emailToRemove: string) => {
setParticipantEmails(participantEmails.filter(email => email !== emailToRemove));
};
const validateForm = () => {
const newErrors: FormErrors = {};
if (!title.trim()) {
newErrors.title = "Title is required";
}
if (!startTime) {
newErrors.startTime = "Start time is required";
}
if (!endTime) {
newErrors.endTime = "End time is required";
}
if (startTime && endTime && new Date(startTime) >= new Date(endTime)) {
newErrors.endTime = "End time must be after start time";
}
if (startTime && new Date(startTime) < new Date()) {
newErrors.startTime = "Start time cannot be in the past";
}
return newErrors;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const formErrors = validateForm();
if (Object.keys(formErrors).length > 0) {
setErrors(formErrors);
return;
}
setIsLoading(true);
try {
const response = await apiClient.post("/meetings", {
data: {
title,
startTime,
endTime,
isActive: false,
participantEmails,
},
});
if (response.data.meta?.invalidEmails?.length > 0) {
// Handle invalid emails if needed
console.warn("Some emails were invalid:", response.data.meta.invalidEmails);
}
router.push("/meetings");
} catch (error) {
console.error("Failed to create meeting:", error);
// You might want to show an error notification here
} finally {
setIsLoading(false);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-6 max-w-lg mx-auto">
<div>
<label className="block text-sm font-medium text-gray-100">
Meeting Title
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
className={`mt-1 block w-full rounded-md border text-gray-600 border-gray-300 px-3 py-2 ${
errors.title ? 'border-red-500' : ''
}`}
required
/>
{errors.title && (
<p className="mt-1 text-sm text-red-500">{errors.title}</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-100">
Start Time
</label>
<input
type="datetime-local"
value={startTime}
onChange={(e) => setStartTime(e.target.value)}
className={`mt-1 block w-full rounded-md border text-gray-600 border-gray-300 px-3 py-2 ${
errors.startTime ? 'border-red-500' : ''
}`}
required
/>
{errors.startTime && (
<p className="mt-1 text-sm text-red-500">{errors.startTime}</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-100">
End Time
</label>
<input
type="datetime-local"
value={endTime}
onChange={(e) => setEndTime(e.target.value)}
className={`mt-1 block w-full rounded-md border text-gray-600 border-gray-300 px-3 py-2 ${
errors.endTime ? 'border-red-500' : ''
}`}
required
/>
{errors.endTime && (
<p className="mt-1 text-sm text-red-500">{errors.endTime}</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-100">
Add Participants
</label>
<div className="flex gap-2">
<div className="flex-1">
<div className="relative">
<Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addParticipant();
}
}}
placeholder="Enter email address"
className={`mt-1 block w-full rounded-md border text-gray-600 border-gray-300 pl-10 pr-3 py-2 ${
errors.email ? 'border-red-500' : ''
}`}
/>
</div>
{errors.email && (
<p className="mt-1 text-sm text-red-500">{errors.email}</p>
)}
</div>
<button
type="button"
onClick={addParticipant}
className="mt-1 p-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
<Plus size={20} />
</button>
</div>
{participantEmails.length > 0 && (
<div className="mt-3 space-y-2">
{participantEmails.map((email) => (
<div
key={email}
className="flex items-center justify-between p-2 bg-gray-700 rounded-md"
>
<span className="text-sm text-gray-200">{email}</span>
<button
type="button"
onClick={() => removeParticipant(email)}
className="text-gray-400 hover:text-red-500"
>
<X size={16} />
</button>
</div>
))}
</div>
)}
</div>
<div className="flex gap-4">
<button
type="submit"
disabled={isLoading}
className="flex-1 bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{isLoading ? (
<>
<Loader2 className="animate-spin" size={20} />
Creating...
</>
) : (
'Create Meeting'
)}
</button>
<button
type="button"
onClick={() => router.push("/meetings")}
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-700"
>
Cancel
</button>
</div>
</form>
);
}
```
The above code creates a new meeting that uses the `apiClient` we set up earlier. It manages form state for meeting details (`title`, `start/end` times) and `participant` emails using React's `useState` hooks. The form includes client-side validation for emails and meeting times, with a neat feature that lets users add multiple participant emails through a dynamic list interface. When the form is submitted, it validates all inputs, sends the data to the server using the `apiClient`, and handles invalid email responses.
![Screenshot 2024-10-24 at 11.15.07](https://hackmd.io/_uploads/ryCHR5wlJg.png)
Now update your `app/page.tsx` file to render the `MeetingsPage`:
```typescript
import MeetingsPage from "./meetings/page";
export default function Home() {
return <MeetingsPage />;
}
```
## Conclusion
We've successfully set up the front end of our Google Meet clone with Next.js. We've implemented the following:
- User authentication with Zustand
- Protected routes with middleware
- Meeting management interface, listing meetings, and creating new meetings.
- Responsive UI with Tailwind CSS
In Part 3, we'll add real-time video conferencing using WebRTC, Chat functionality, Screen sharing capabilities, Meeting controls and participant management.
The complete source code for this part is available on [GitHub](https://github.com/icode247/google-meet-clone/tree/part_2).