Unit 7.2 · Tutorial 2

Frontend Integration & CI/CD Deployment

Chapter 22 · Capstone Project
~3 hours Advanced Frontend · React Query · CI/CD · Cloud

Overview

With your backend API ready, this tutorial focuses on connecting the frontend, managing state, implementing data fetching with React Query, setting up CI/CD pipelines with GitHub Actions, and deploying to the cloud. By the end, your full‑stack application will be live and accessible to users.

Why this matters: CI/CD automates testing and deployment, ensuring your application is always in a deployable state. Cloud deployment makes your application accessible to the world.

1. Frontend Setup

Set up your React (or chosen framework) project with the necessary dependencies for API integration.

# Create React app (or Vite) npm create vite@latest my-app -- --template react-ts cd my-app npm install # Install dependencies npm install @tanstack/react-query axios npm install react-router-dom npm install -D @types/react-router-dom

Project structure

src/ ├── api/ │ ├── client.ts # Axios instance │ └── hooks/ # React Query hooks ├── components/ │ ├── common/ │ └── features/ ├── pages/ ├── hooks/ # Custom hooks ├── types/ └── utils/

2. API Integration with React Query

React Query handles server‑state management, caching, and background updates.

// api/client.ts – Axios instance import axios from 'axios'; export const apiClient = axios.create({ baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api/v1', headers: { 'Content-Type': 'application/json', }, }); apiClient.interceptors.request.use((config) => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; });
// api/hooks/useProducts.ts import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { apiClient } from '../client'; export const useProducts = (page = 1, limit = 10) => { return useQuery({ queryKey: ['products', page, limit], queryFn: async () => { const { data } = await apiClient.get(`/products?page=${page}&limit=${limit}`); return data; } }); }; export const useCreateProduct = () => { const queryClient = useQueryClient(); return useMutation({ mutationFn: (newProduct) => apiClient.post('/products', newProduct), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['products'] }); } }); };
// main.tsx – React Query Provider import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const queryClient = new QueryClient(); ReactDOM.createRoot(document.getElementById('root')!).render( );

3. State Management (Zustand)

Use Zustand for client‑side global state (UI state, authentication, etc.).

// stores/authStore.ts import { create } from 'zustand'; import { persist } from 'zustand/middleware'; interface AuthState { user: User | null; token: string | null; login: (token: string, user: User) => void; logout: () => void; } export const useAuthStore = create()( persist( (set) => ({ user: null, token: null, login: (token, user) => set({ token, user }), logout: () => set({ token: null, user: null }), }), { name: 'auth-storage' } ) );
// Use in component const { user, login, logout } = useAuthStore(); // ...
Separation: React Query handles server state; Zustand handles client state (UI, auth, etc.). This separation keeps your code clean.

4. CI/CD Setup (GitHub Actions)

Automate testing and deployment with GitHub Actions.

# .github/workflows/deploy.yml name: Deploy on: push: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18 - run: npm ci - run: npm run test deploy-backend: needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Deploy to Render/Heroku run: | # Deploy backend - name: Deploy frontend run: | # Deploy frontend to Vercel/Netlify

5. Cloud Deployment

Frontend: Vercel / Netlify

# vercel.json { "buildCommand": "npm run build", "outputDirectory": "dist", "rewrites": [ { "source": "/(.*)", "destination": "/" } ] }

Backend: Render / Heroku / AWS

# render.yaml services: - type: web name: my-api env: node buildCommand: npm ci && npm run build startCommand: npm run start:prod envVars: - key: NODE_ENV value: production - key: DATABASE_URL sync: false
Tips:
  • Use environment variables for sensitive data.
  • Set up health checks for your API.
  • Enable logging and monitoring.

Quiz

Question 1

Which library is recommended for server‑state management in React?

  • Redux
  • React Query (TanStack Query)
  • Zustand
  • Context API
Show answer
B. React Query (TanStack Query).

Question 2

What does the invalidateQueries function do in React Query?

  • Deletes all cached data
  • Marks cached data as stale and triggers a refetch
  • Updates the cache with new data
  • Clears all query keys
Show answer
B. Marks cached data as stale and triggers a refetch.

Question 3

Which cloud platform is recommended for hosting a React frontend?

  • AWS EC2
  • Vercel or Netlify
  • Heroku
  • DigitalOcean
Show answer
B. Vercel or Netlify (optimised for static sites and SPAs).

Exercises

Exercise 1

Create a React Query hook for fetching a single product by ID with error handling.

Sample answer
export const useProduct = (id: number) => { return useQuery({ queryKey: ['product', id], queryFn: async () => { const { data } = await apiClient.get(`/products/${id}`); return data; }, enabled: !!id, retry: 1 }); };

Exercise 2

Write a GitHub Actions workflow that runs tests on every push to the main branch.

Sample answer
name: CI on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18 - run: npm ci - run: npm run test - run: npm run build

Homework

Homework 1

Complete the frontend integration for your capstone project. Connect all API endpoints, manage state, and set up CI/CD. Deploy your application to the cloud.

Sample outline
  • Frontend: Complete all pages and components.
  • API: Use React Query for all data fetching.
  • CI/CD: GitHub Actions workflow that tests and deploys.
  • Deployment: Frontend on Vercel/Netlify, Backend on Render/Heroku.
  • Documentation: Update README with live URLs.

Mini‑Project

Full‑Stack Deployment Sprint

Complete the full‑stack deployment of your capstone project:

  • Connect frontend to backend API
  • Implement all data fetching with React Query
  • Set up GitHub Actions for CI/CD
  • Deploy frontend (Vercel) and backend (Render)
  • Test the live application
Sample outline
  • Frontend: Deployed to Vercel at vercel.app
  • Backend: Deployed to Render at onrender.com
  • CI/CD: GitHub Actions runs tests and deploys on push
  • Testing: End‑to‑end test the live application

Tutorial Summary

You connected your frontend to the backend API, implemented data fetching with React Query, managed client state with Zustand, set up CI/CD with GitHub Actions, and deployed your application to the cloud. Your capstone project is now live and production‑ready.

Key takeaway: CI/CD and cloud deployment are essential for modern development. Automating your pipeline reduces errors and accelerates delivery.