Skip to content

feat: build react-spa frontend #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ MYSQL_PASSWORD=test_password
# Server
FASTIFY_CLOSE_GRACE_DELAY=1000
LOG_LEVEL=info
FASTIFY_VITE_DEV_MODE=false

# Security
JWT_SECRET=
RATE_LIMIT_MAX=
RATE_LIMIT_MAX=4 # For tests

6 changes: 5 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ jobs:
- name: Lint Code
run: npm run lint

- name: Build Vite
run: npm run build:client

- name: Generate JWT Secret
id: gen-jwt
run: |
Expand All @@ -61,11 +64,12 @@ jobs:

- name: Test
env:
# JWT_SECRET is dynamically generated and loaded from the environment
MYSQL_HOST: localhost
MYSQL_PORT: 3306
MYSQL_DATABASE: test_db
MYSQL_USER: test_user
MYSQL_PASSWORD: test_password
# JWT_SECRET is dynamically generated and loaded from the environment
RATE_LIMIT_MAX: 4
FASTIFY_VITE_DEV_MODE: false
run: npm run db:migrate && npm run test
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Install the dependencies:
npm install
```

Configure a `.env` file, see [.env.example](/.env.example) at root of the project.


### Database
You can run a MySQL instance with Docker:
```bash
Expand Down
5 changes: 5 additions & 0 deletions client/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function App () {
return (
<p>Welcome to the official Fastify demo!</p>
)
}
13 changes: 13 additions & 0 deletions client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link data-rh="true" rel="icon" href="/favicon.ico" />
<title>Fastify demo</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/mount.tsx"></script>
</body>
</html>
7 changes: 7 additions & 0 deletions client/mount.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { createRoot } from 'react-dom/client'
import { App } from './App'

const rootElement = document.getElementById('root')!

const root = createRoot(rootElement)
root.render(<App />)
Binary file added client/public/favicon.ico
Binary file not shown.
23 changes: 23 additions & 0 deletions client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"composite": true,
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["**/*"],
}
1 change: 1 addition & 0 deletions client/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
14 changes: 10 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ services:
db:
image: mysql:8.4
environment:
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
ports:
- 3306:3306
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-u${MYSQL_USER}", "-p${MYSQL_PASSWORD}"]
interval: 10s
timeout: 5s
retries: 3
volumes:
- db_data:/var/lib/mysql

volumes:
db_data:
13 changes: 9 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
"test": "test"
},
"scripts": {
"start": "npm run build && fastify start -l info dist/app.js",
"start": "npm run build && npm run build:client && fastify start -l info dist/app.js",
"build": "tsc",
"build:client": "vite build",
"watch": "tsc -w",
"dev": "npm run build && concurrently -k -p \"[{name}]\" -n \"TypeScript,App\" -c \"yellow.bold,cyan.bold\" \"npm:watch\" \"npm:dev:start\"",
"dev:start": "fastify start --ignore-watch=.ts$ -w -l info -P dist/app.js",
"dev:start": "fastify start --ignore-watch=.ts$ -l info -P dist/app.js",
"test": "npm run db:seed && tap --jobs=1 test/**/*",
"standalone": "node --env-file=.env dist/server.js",
"lint": "eslint --ignore-pattern=dist",
"lint": "eslint test src client vite.config.js",
"lint:fix": "npm run lint -- --fix",
"db:migrate": "node --env-file=.env scripts/migrate.js",
"db:seed": "node --env-file=.env scripts/seed-database.js"
Expand All @@ -36,12 +37,16 @@
"@fastify/swagger-ui": "^5.0.1",
"@fastify/type-provider-typebox": "^5.0.0",
"@fastify/under-pressure": "^9.0.1",
"@fastify/vite": "^7.0.1",
"@sinclair/typebox": "^0.33.12",
"@vitejs/plugin-react": "^4.3.1",
"concurrently": "^9.0.1",
"fastify": "^5.0.0",
"fastify-cli": "^7.0.0",
"fastify-plugin": "^5.0.1",
"postgrator": "^7.3.0"
"postgrator": "^7.3.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/node": "^22.5.5",
Expand Down
48 changes: 38 additions & 10 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import path from 'node:path'
import fastifyAutoload from '@fastify/autoload'
import { FastifyInstance, FastifyPluginOptions } from 'fastify'
import fastifyVite from '@fastify/vite'

export const options = {
ajv: {
Expand All @@ -19,29 +20,30 @@ export default async function serviceApp (
fastify: FastifyInstance,
opts: FastifyPluginOptions
) {
delete opts.skipOverride // This option only serves testing purpose
const { registerVite = true } = opts

// This loads all external plugins defined in plugins/external
// those should be registered first as your custom plugins might depend on them
await fastify.register(fastifyAutoload, {
dir: path.join(import.meta.dirname, 'plugins/external'),
options: { ...opts }
options: {}
})

// This loads all your custom plugins defined in plugins/custom
// those should be support plugins that are reused
// through your application
fastify.register(fastifyAutoload, {
await fastify.register(fastifyAutoload, {
dir: path.join(import.meta.dirname, 'plugins/custom'),
options: { ...opts }
options: {}
})

// This loads all plugins defined in routes
// define your routes in one of these
fastify.register(fastifyAutoload, {
await fastify.register(fastifyAutoload, {
dir: path.join(import.meta.dirname, 'routes'),
autoHooks: true,
cascadeHooks: true,
options: { ...opts }
options: {}
})

fastify.setErrorHandler((err, request, reply) => {
Expand All @@ -58,11 +60,12 @@ export default async function serviceApp (
'Unhandled error occurred'
)

reply.code(err.statusCode ?? 500)

let message = 'Internal Server Error'
if (err.statusCode === 401) {
message = err.message
const statusCode = err.statusCode ?? 500
reply.code(statusCode)

if (statusCode === 429) {
message = 'Rate limit exceeded'
}

return { message }
Expand Down Expand Up @@ -92,5 +95,30 @@ export default async function serviceApp (
reply.code(404)

return { message: 'Not Found' }
}
)

if (registerVite) {
/* c8 ignore start - We don't launch the spa tests with the api tests */
// We setup the SPA
await fastify.register(fastifyVite, function (fastify) {
return {
root: path.resolve(import.meta.dirname, '../'),
dev: fastify.config.FASTIFY_VITE_DEV_MODE,
spa: true
}
})

// Route must match vite "base": https://vitejs.dev/config/shared-options.html#base
fastify.get('/', (req, reply) => {
return reply.html()
})

await fastify.vite.ready()
/* c8 ignore end */
} else {
fastify.get('/', () => {
return 'Vite is not registered.'
})
}
}
7 changes: 7 additions & 0 deletions src/plugins/external/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ declare module 'fastify' {
MYSQL_DATABASE: string;
JWT_SECRET: string;
RATE_LIMIT_MAX: number;
FASTIFY_VITE_DEV_MODE: boolean;
};
}
}
Expand Down Expand Up @@ -52,6 +53,12 @@ const schema = {
RATE_LIMIT_MAX: {
type: 'number',
default: 100
},

// Frontend
FASTIFY_VITE_DEV_MODE: {
type: 'boolean',
default: true
}
}
}
Expand Down
24 changes: 0 additions & 24 deletions src/routes/home.ts

This file was deleted.

1 change: 1 addition & 0 deletions test/app/rate-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ it('should be rate limited', async (t) => {
url: '/'
})

assert.equal(res.body, 'Vite is not registered.')
assert.strictEqual(res.statusCode, 200)
}

Expand Down
3 changes: 2 additions & 1 deletion test/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const AppPath = path.join(import.meta.dirname, '../src/app.ts')
// needed for testing the application
export function config () {
return {
skipOverride: 'true' // Register our application with fastify-plugin
skipOverride: true, // Register our application with fastify-plugin
registerVite: false
}
}

Expand Down
10 changes: 4 additions & 6 deletions test/routes/api/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ test('GET /api without authorization header', async (t) => {
url: '/api'
})

assert.deepStrictEqual(JSON.parse(res.payload), {
message: 'No Authorization was found in request.headers'
})
assert.equal(res.statusCode, 401)
assert.deepStrictEqual(JSON.parse(res.payload).message, 'No Authorization was found in request.headers')
})

test('GET /api without JWT Token', async (t) => {
Expand All @@ -25,9 +24,8 @@ test('GET /api without JWT Token', async (t) => {
}
})

assert.deepStrictEqual(JSON.parse(res.payload), {
message: 'Authorization token is invalid: The token is malformed.'
})
assert.equal(res.statusCode, 401)
assert.deepStrictEqual(JSON.parse(res.payload).message, 'Authorization token is invalid: The token is malformed.')
})

test('GET /api with JWT Token', async (t) => {
Expand Down
14 changes: 0 additions & 14 deletions test/routes/home.test.ts

This file was deleted.

2 changes: 1 addition & 1 deletion test/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": "../tsconfig.json",
"compilerOptions": {
"baseUrl": ".",
"noEmit": false
"noEmit": false,
},
"include": ["@types", "../src/**/*.ts", "**/*.ts"]
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"outDir": "dist",
"rootDir": "src"
},
"include": ["@types", "src/**/*.ts"]
"include": ["@types", "src/**/*.ts"],
}
13 changes: 13 additions & 0 deletions vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { resolve } from 'node:path'
import viteReact from '@vitejs/plugin-react'

/** @type {import('vite').UserConfig} */
export default {
base: '/',
root: resolve(import.meta.dirname, 'client'),
build: {
emptyOutDir: true,
outDir: resolve(import.meta.dirname, 'dist/client')
},
plugins: [viteReact()]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you're using tsc to build the server code into the dist directory, I personally think it's kind of weird to have the client code built to src/client/dist. I prefer to add the following here to the vite config:

build: {
  emptyOutDir: true, // optional
  outDir: resolve(import.meta.dirname, 'dist/client'),
}

Additionally, I'm trying to get this PR into fastify-vite which gives another vite plugin called viteFastify() that helps with production builds.

}