• Stars
    star
    681
  • Rank 66,346 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created almost 4 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This project is a small but feature complete application build with Fastify and Svelte, and it aims to show all the core concepts of Fastify, best practices, and recommendations.

Fastify App Example

This project is a small but feature complete application build with Fastify and Svelte, and it aims to show all the core concepts of Fastify, best practices, and recommendations.

There is no attached blog post or tutorial, you should go through the application code and read the code comments, which will explain you best practices, protips, suggestions and so forth, I hope you will like it!

What is this application doing?

This application is an URL shortener, it exposes an admin UI and a series of routes under the /_app prefix. Any other request will be interpreted as redirect. If a redirect does not exists, the user will either see a standard 404 page, or a page with a series of suggestions generated by Elasticsearch (both this pages are server side rendered!).

The admin logins via GitHub OAuth, the application is also protected by a rate limiter and during development it exposes a Swagger UI with every endpoint. Read the next section to understand how the project works and how it is recommended to explore it.

Project structure

The project follows a well established pattern within the Fastify community, it has two top level folders, plugins and routes.

project structure

The first one contains all the code that should be shared across your entire aplication, such as authentication and rate limiting, while the second one contains all the business logic, such as the redirect code and the admin APIs.

We recommend to follow this pattern, you can generate a project with the same structure by using fastify-cli.

How should I read through the comments?

You can read the project in any order, but I would recommend the following:

  1. app.js
  2. plugins/authorization.js
  3. plugins/elasticsearch.js
  4. plugins/rate-limit.js
  5. plugins/validUrl.js
  6. plugins/swagger.js
  7. routes/status.js
  8. routes/frontend.js
  9. routes/admin.js
  10. routes/redirect/index.js
  11. routes/redirect/update-count.js
  12. routes/redirect/worker.cjs
  13. routes/redirect/App.svelte
  14. ui/*
  15. test/helper.js
  16. test/plugins/validUrl.test.js
  17. test/routes/status.test.js
  18. test/routes/admin.test.js.test.js
  19. test/routes/redirect.test.js.test.js

FAQ

You are using ESM, how are you compiling the project?

I'm not. From Node.js v12.20 and Node.js v14 ES Modules are supported out of the box. As you can see in the package.json, there is a new field: { "type": "module" }. That field will instruct Node.js that the project is using ESM instead of CJS (common js, which is require/module.exports), and every .js file will be a ESM module, while every .cjs file will be a CJS module.

A follow up question you can ask now is: "why is there a rollup.config.js? Great question! That is used for compiling the Svelte frontend locatated in ui/.

Can I use TypeScript?

Yes! Fastify supports TypeScript out of the box! The project is written in plain JavaScript because I didn't want to add too many things to the project, but probably in the future there will be a branch with a TypeScript implementation.

Why aren't you using a try-catch block in route declarations?

Fastify supports promises/async-await out of the box. Everything is handled for you, if you throw an error inside a route handler (same goes for hooks or plugins) the error will be caught automatically by Fastify and return the most approriate error.

Why Svelte?

No specific reason, any frontend framework will do the job well. I used Svelte because I like it and because it makes it very easy to think about the frontend, without making me think too much about how something should be written or weird APIs, but directly focusing on the business logic while writing almost plain html/css/js.

How to run this project

  1. Create an .env file from the template:

    cp .env.template .env
  2. Create a new GitHub OAuth application here, then copy the app id and secret and add them to the env file:

    GITHUB_APP_ID=<app-id>
    GITHUB_APP_SECRET=<app-secret>
  3. Add your primary GitHub email to the ALLOWED_USERS variable:

    ALLOWED_USERS=<your-primary-github-mail>
  4. Run the keys-generator script and store the result in the COOKIE_SECRET env variable:

    node scripts/keys-generator.js
    COOKIE_SECRET=<generated-key>

Now you can either run the project locally or deploy it.

Locally

  1. Use Node.js v18.

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
    nvm install 18
    node -v # should be v18.minor.patch
  2. Install the project dependencies:

    npm install
  3. In a separate terminal window, run Elasticsearch:

    npm run elasticsearch
  4. Once Elasticsearch is up and running, run the prepare-elasticsearch script and copy the result in the ELASTIC_URL and ELASTIC_API_KEY env variables:

    node scripts/prepare-elasticsearch.js
    ELASTIC_ADDRESS=<result.address>
    ELASTIC_API_KEY=<result.apiKey>
  5. You are all set! Run the project with thw following command:

    npm run dev

Deploy

This section contains instructions for deploying this application.

Would you like to see more recipes? Open an issue. Do you already have a deploy recipe and want to share it? That's awesome, send a pull request!

Cloud Run

Open deploy-recipes/cloud-run, you will find everything you need there.

Elastic Cloud

You can create an Elasticsearch cluster with Elastic Cloud, with a free 14-day trial of the Elasticsearch Service.

Contribute

Feel free to send pull request with new features, bugfix or documentation improvements!

Questions

Open an issue or take a look at our fastify/help repository. We also have a Discord community you can join.

If you have any question related to Elasticsearch or the Elasticsearch client, you can open a new discussion on discuss.elastic.co or in the client issue tracker.

License

This software is licensed under the Apache 2 license.

More Repositories

1

find-my-way

A crazy fast HTTP router
JavaScript
1,444
star
2

electron-is

An 'is' utility for Electron which provides a set of handy functions, with a self-descriptive name.
JavaScript
218
star
3

hpagent

A ready to use http and https agent for working with proxies that keeps connections alive!
JavaScript
182
star
4

router-benchmark

Benchmark of the most commonly used http routers
JavaScript
77
star
5

Tyval

Fast and extensible validator for JavaScript
JavaScript
61
star
6

fastify-architecture-workshop

JavaScript
57
star
7

workq

A super tiny work queue
JavaScript
38
star
8

fast-decode-uri-component

Fast and safe decodeURIComponent
JavaScript
29
star
9

easy-breaker

A simple and low overhead circuit breaker utility.
JavaScript
20
star
10

appversion

AppVersion is a CLI tool whose purpose is to provide a unique manager of the version of you application.
JavaScript
17
star
11

LightFirewall

Lightweight firewall built for NodeJs.
JavaScript
17
star
12

fastify-101

Learn Fastify talk!
14
star
13

rinvoke

RPC library based on net sockets, can work both with tcp sockets and ipc.
JavaScript
12
star
14

monoliths-always-pay-their-debts

JavaScript
11
star
15

What-if-I-told-you-that-HTTP-can-be-fast

Fastify and node performances talk.
JavaScript
8
star
16

fast-json-body

Parse your json body at max speed and safely.
JavaScript
7
star
17

yaml-template

Declare js objects with style using yaml syntax.
JavaScript
7
star
18

semver-store

An extremely fast semver based store.
JavaScript
7
star
19

pino-to-ecs

Converts Pino logs to Elastic Common Schema.
JavaScript
6
star
20

electron-screen

Small Module that returns an array with all the monitors connected to the pc with their resolution and position.
C++
5
star
21

diapo

Easy to use, markdown based presentation framework with sane defaults.
JavaScript
4
star
22

demodb

An HTTP based database for demo purposes, workshop and so on.
JavaScript
3
star
23

Microservices

Microservices architectural studies
JavaScript
3
star
24

is-elasticsearch-running

A small utility to verify if an Elasticsearch cluster is up and running.
JavaScript
2
star
25

YourMomBot

A simple "How is your mom" telegram bot.
JavaScript
2
star
26

dotfiles

My dotfiles.
Vim Script
2
star
27

undici-proxy-example

JavaScript
2
star
28

FileFactory

FileFactory is a easy to use utility for managing files built for Cordova, compatible with Angular and Ionic.
JavaScript
2
star
29

YahooWeatherProcessing

Yahoo Weather library for Processing
Java
2
star
30

maptd-workshop

Monolith always pay their debts - workshop code
JavaScript
2
star
31

old-FilmHunter

Movie Search WebApp
JavaScript
1
star
32

fast-iterator

Fast execution of an array of functions with the same value as input that can be altered.
JavaScript
1
star
33

omxloop

Script for looping Omxplayer.
Shell
1
star
34

self-stream

A small node module that streams your transformations to the same file
JavaScript
1
star
35

shape-of-q

A simple and fast redis based queue, supports both fifo and lifo.
JavaScript
1
star
36

SCaaS

SuperCazzola as a Service
JavaScript
1
star
37

why-we-built-another-framework

JavaScript
1
star
38

dom.js

Dom manipulation library, super early alpha.
JavaScript
1
star
39

whatwg-headers

JavaScript
1
star
40

Language-Based-Security

Repository of the exercises and the project of the Chalmers Language-Based Security Course.
JavaScript
1
star