Stacky
Stacky

Reputation: 3

Fastify reload browser

In Fastify framework is there anyway to reflesh the browser when changes happen on save. In Express we have npm livereload as a middleware to listen to backend changes in Express. Are there any similar functions in Fastify or do I have to write my own registered plugin to automatically reflesh the browser on backend changes?

Upvotes: 0

Views: 3428

Answers (2)

IObert
IObert

Reputation: 3816

The livereload package that you mentioned is a general-purpose tool that works with Fastify as well. I was able to make it run with the following packages:

  • typescript Running tsc -w -outdir dist/ to watch the .ts files and transpile them into .js files
  • nodemon Running nodemon -r dotenv/config dist/server.js to watch the .js files and restart the web server
  • livereload Running livereload ./dist/ -w 500 so that the browser refreshes once the server restarted
  • concurrently To tie it all together in the package.json
    "scripts": {
      "build": "tsc",
      "start": "node -r dotenv/config dist/server.js",
      "dev:tsc": "tsc -w -outdir dist/",
      "dev:watch": "nodemon -r dotenv/config dist/server.js",
      "dev:livereload": "livereload ./dist/ -w 500",
      "dev": "concurrently -k -p \"[{name}]\" -n \"TypeScript,App,LiveReload\" -c \"yellow.bold,cyan.bold,green.bold\" \"yarn dev:tsc\" \"yarn dev:watch\" \"yarn dev:livereload\" "
    },
    

Note that you need to include the following <script> tag in your .html files to make livereload work

<script>
    document.write(
      '<script src="http://' +
        (location.host || "localhost").split(":")[0] +
        ':35729/livereload.js?snipver=1"></' +
        "script>"
    );
</script>

This was enough to make my small Fastify project run, your milage may vary.

Upvotes: 2

Manuel Spigolon
Manuel Spigolon

Reputation: 12880

Yes, there is the fastify-cli module for that: https://github.com/fastify/fastify-cli

it has the --watch option that you can use to live reload your backend on file changes.

In your package.json add this script:

 "dev": "fastify start -l info --watch --pretty-logs app.js",

Note that app.js must expose this interface:

module.exports = function (fastify, ops, next) {
  next()
}

Upvotes: 0

Related Questions