Open
Conversation
# 🌟 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)**
```bash
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`:
```javascript
// 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`:
```javascript
// 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:
```json
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
```
Buat fail `.env` (pilihan):
```
PORT=5000
```
---
## ⚛️ **Langkah 2: Membina Frontend (React)**
Kembali ke direktori utama:
```bash
cd ..
npx create-react-app client
cd client
```
Edit `src/App.js`:
```javascript
// 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:
```json
"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
```gitignore
# 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
```bash
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:**
```bash
gh repo create codepaul/codepaul --public --source=. --remote=origin --push
```
### 4.4 Sambungkan repositori tempatan ke GitHub
```bash
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`:
```yaml
# .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:
```bash
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](https://render.com) atau [Railway](https://railway.app)
- 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](https://vercel.com) atau [Netlify](https://netlify.com)
- 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
```markdown
# 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](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:
```yaml
provenance:
needs: build
uses: slsa-framework/slsa-github-generator/.github/workflows/generator-generic-ossf-slsa3-publish.yml@v1.7.0
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!** 🚀
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🌟 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
🧰 Prasyarat
🛠 Langkah 1: Membina Backend (Node.js + Express)
Buat fail
server.js:Buat fail
routes/api.js:Dalam
server/package.json, tambah skrip:Buat fail
.env(pilihan):⚛️ Langkah 2: Membina Frontend (React)
Kembali ke direktori utama:
Edit
src/App.js:Dalam
client/package.json, tambah baris berikut untuk memudahkan panggilan API semasa pembangunan:🧪 Langkah 3: Uji Secara Tempatan
cd server && npm run devcd client && npm starthttp://localhost:3000– anda sepatutnya dapat melihat dan menambah item.📦 Langkah 4: Sedia untuk Git dan GitHub
4.1 Buat fail
.gitignoredi root projek4.2 Initialize Git dan commit
4.3 Cipta repositori di GitHub
Kaedah 1 – melalui laman web:
codepaul(atau apa‑apa nama)Kaedah 2 – menggunakan GitHub CLI:
4.4 Sambungkan repositori tempatan ke GitHub
Gantikan URL dengan repositori anda.
🔄 Langkah 5: CI/CD dengan GitHub Actions
Buat direktori
.github/workflowsdan failci-cd.yml:Commit dan push fail ini:
git add .github/ git commit -m "Add CI/CD workflow" git pushSekarang, setiap push ke
mainakan menjalankan pipeline. Anda boleh melihatnya di tab Actions repositori GitHub.🚀 Langkah 6: Deployment (Pilihan)
6.1 Deploy backend ke Render atau Railway
npm start(dalam direktoriserver).6.2 Deploy frontend ke Vercel atau Netlify
client.REACT_APP_API_URLditetapkan ke URL backend yang telah dideploy.6.3 (Lanjutan) Integrasi deployment dalam GitHub Actions Anda boleh menambah langkah selepas
builduntuk deploy automatik menggunakan token rahsia (GitHub Secrets).📄 Langkah 7: Dokumentasi dan Lesen
7.1 Edit
README.mddi root projek7.2 Tambah lesen MIT
Buat fail
LICENSEdan 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:
Ini memerlukan konfigurasi tambahan dan hanya relevan jika anda ingin memenuhi piawaian SLSA.
✅ Semua Sedia!
Kini anda mempunyai:
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! 🚀