🌟 Projek codepaul: Panduan Lengkap – React + Node.js + Express + GitHub Actions
Anda telah melalui pelbagai perbincangan: daripada pengenalan SLSA, kepada pembangunan aplikasi penuh dengan React, Node.js, Express, dan GitHub Actions, sehingga penciptaan repositori GitHub. Kini tiba masanya untuk menggabungkan semua elemen menjadi satu panduan lengkap yang boleh terus anda gunakan.
Di bawah adalah resipi lengkap untuk membina, menyambung, dan mengautomasikan projek codepaul – sebuah aplikasi full‑stack dengan React di frontend, Node.js/Express di backend, dan CI/CD menggunakan GitHub Actions. Semua kod dan arahan disertakan.
📁 Struktur Projek
codepaul/
├── client/ # React frontend
│ ├── public/
│ │ └── index.html
│ ├── src/
│ │ ├── App.js
│ │ ├── App.css
│ │ ├── index.js
│ │ └── components/
│ │ └── Hello.js
│ ├── package.json
│ └── README.md
├── server/ # Node.js/Express backend
│ ├── routes/
│ │ └── api.js
│ ├── server.js
│ ├── package.json
│ └── .env
├── .github/
│ └── workflows/
│ └── ci-cd.yml
├── .gitignore
├── README.md
└── LICENSE
🧰 Prasyarat
- Node.js (v18 atau lebih baru)
- npm atau yarn
- Git
- Akaun GitHub
🛠 Langkah 1: Membina Backend (Node.js + Express)
mkdir codepaul
cd codepaul
mkdir server
cd server
npm init -y
npm install express cors dotenv
npm install --save-dev nodemon
Buat fail server.js:
// server/server.js
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use('/api', require('./routes/api'));
app.get('/health', (req, res) => {
res.json({ status: 'OK', message: 'Server berjalan' });
});
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Buat fail routes/api.js:
// server/routes/api.js
const express = require('express');
const router = express.Router();
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
];
router.get('/items', (req, res) => res.json(items));
router.post('/items', (req, res) => {
const newItem = { id: items.length + 1, name: req.body.name };
items.push(newItem);
res.status(201).json(newItem);
});
module.exports = router;
Dalam server/package.json, tambah skrip:
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
Buat fail .env (pilihan):
⚛️ Langkah 2: Membina Frontend (React)
Kembali ke direktori utama:
cd ..
npx create-react-app client
cd client
Edit src/App.js:
// client/src/App.js
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState('');
useEffect(() => {
fetch('/api/items')
.then(res => res.json())
.then(setItems)
.catch(console.error);
}, []);
const addItem = async (e) => {
e.preventDefault();
if (!newItem.trim()) return;
try {
const res = await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newItem }),
});
const item = await res.json();
setItems([...items, item]);
setNewItem('');
} catch (err) {
console.error(err);
}
};
return (
<div className="App">
<h1>Senarai Item</h1>
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
<form onSubmit={addItem}>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
placeholder="Nama item baru"
/>
<button type="submit">Tambah</button>
</form>
</div>
);
}
export default App;
Dalam client/package.json, tambah baris berikut untuk memudahkan panggilan API semasa pembangunan:
"proxy": "http://localhost:5000"
🧪 Langkah 3: Uji Secara Tempatan
- Terminal 1 (backend):
cd server && npm run dev
- Terminal 2 (frontend):
cd client && npm start
- Buka
http://localhost:3000 – anda sepatutnya dapat melihat dan menambah item.
📦 Langkah 4: Sedia untuk Git dan GitHub
4.1 Buat fail .gitignore di root projek
# dependencies
node_modules/
package-lock.json
yarn.lock
# environment
.env
.env.local
# build
dist/
build/
# logs
*.log
npm-debug.log*
4.2 Initialize Git dan commit
git init
git add .
git commit -m "Initial commit: React + Node.js + Express"
4.3 Cipta repositori di GitHub
Kaedah 1 – melalui laman web:
- Log masuk ke GitHub, klik + → New repository
- Nama repositori:
codepaul (atau apa‑apa nama)
- Jangan pilih mana‑mana pilihan inisialisasi
- Klik Create repository
Kaedah 2 – menggunakan GitHub CLI:
gh repo create codepaul/codepaul --public --source=. --remote=origin --push
4.4 Sambungkan repositori tempatan ke GitHub
git remote add origin https://github.com/codepaul/codepaul.git
git branch -M main
git push -u origin main
Gantikan URL dengan repositori anda.
🔄 Langkah 5: CI/CD dengan GitHub Actions
Buat direktori .github/workflows dan fail ci-cd.yml:
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install backend dependencies
working-directory: ./server
run: npm ci
- name: Install frontend dependencies
working-directory: ./client
run: npm ci
- name: Build frontend
working-directory: ./client
run: npm run build
- name: Run backend tests (jika ada)
working-directory: ./server
run: npm test || echo "No tests yet"
- name: Run frontend tests
working-directory: ./client
run: npm test -- --watchAll=false || echo "No tests yet"
Commit dan push fail ini:
git add .github/
git commit -m "Add CI/CD workflow"
git push
Sekarang, setiap push ke main akan menjalankan pipeline. Anda boleh melihatnya di tab Actions repositori GitHub.
🚀 Langkah 6: Deployment (Pilihan)
6.1 Deploy backend ke Render atau Railway
- Buat akaun dan sambungkan repositori GitHub.
- Tetapkan arahan mula:
npm start (dalam direktori server).
- Tetapkan pemboleh ubah persekitaran jika perlu.
6.2 Deploy frontend ke Vercel atau Netlify
- Import repositori GitHub, tetapkan root direktori ke
client.
- Pastikan pemboleh ubah
REACT_APP_API_URL ditetapkan ke URL backend yang telah dideploy.
6.3 (Lanjutan) Integrasi deployment dalam GitHub Actions Anda boleh menambah langkah selepas build untuk deploy automatik menggunakan token rahsia (GitHub Secrets).
📄 Langkah 7: Dokumentasi dan Lesen
7.1 Edit README.md di root projek
# codepaul – Full‑Stack React + Node.js + Express
Aplikasi contoh dengan React frontend, Node.js/Express backend, dan CI/CD menggunakan GitHub Actions.
## Teknologi
- React (create‑react‑app)
- Node.js + Express
- GitHub Actions
## Cara menjalankan
1. Klon repositori
2. Pasang dependencies: `cd server && npm install` dan `cd client && npm install`
3. Jalankan backend: `cd server && npm run dev`
4. Jalankan frontend: `cd client && npm start`
5. Buka http://localhost:3000
## CI/CD
Setiap push ke `main` akan menjalankan pipeline GitHub Actions (lihat tab Actions).
## Lesen
MIT
7.2 Tambah lesen MIT
Buat fail LICENSE dan salin teks dari https://opensource.org/licenses/MIT. Gantikan tahun dan nama.
🎁 Bonus: Integrasi SLSA (Jika Diperlukan)
Daripada perbincangan sebelum ini, anda boleh menambah SLSA Level 3 provenance menggunakan workflow generator-generic-ossf-slsa3-publish.yml. Contohnya, dalam fail workflow yang sama, selepas langkah build, anda boleh panggil reusable workflow tersebut untuk menjana dan menandatangani provenance.
Contoh potongan:
provenance:
needs: build
uses: slsa-framework/slsa-github-generator/.github/workflows/[email protected]
with:
artifact-path: ./client/build # laluan ke artifak yang ingin dibuktikan
permissions:
id-token: write
contents: read
actions: read
Ini memerlukan konfigurasi tambahan dan hanya relevan jika anda ingin memenuhi piawaian SLSA.
✅ Semua Sedia!
Kini anda mempunyai:
- Aplikasi React + Node.js/Express yang berfungsi sepenuhnya.
- Repositori GitHub dengan kod sumber.
- Pipeline CI/CD automatik.
- Dokumentasi dan lesen.
Anda boleh mengklon repositori ini di mana‑mana mesin dan mula membangun dengan segera. Jika ada sebarang soalan atau ingin menambah ciri seperti pangkalan data, autentikasi, atau ujian, beritahu saya – saya sedia membantu!
Selamat membangun, codepaul! 🚀