暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Nextjs 集成 Fastify

程序猿研究所 2021-07-11
2842

Nextjs 本身是用 Express 作为服务端 server,Express 是一个非常优秀的 Nodejs web server, 但是由于性能方面的原因,我个人更喜欢 Fastify 框架,Nextjs 非常容易自定义集成其他的 web server,包括但是不限于 Fastify, Koa, Hapi 等。

集成 fastify 非常简单,官方就有对应的插件,首先创建一个 Nextjs 项目:

    npx create-next-app --ts

    接下来添加 fastify-next 依赖:

      yarn add fastify fastify-nextjs

      如果要自定义 web server 的话,需要在项目目录下添加 server.js
       文件:

        const fastify = require('fastify')()


        fastify.register(require('fastify-nextjs'))
        .after(() => {
        fastify.next('/*')
        });


        fastify.listen(3000, err => {
        if (err) throw err;
        console.log('Server listening on http://localhost:3000')
        })

        然后将 package.json
         的脚本命令修改成:

            "scripts": {
          "dev": "node server.js",
          "build": "next build",
          "start": "NODE_ENV=production node server.js",
          "lint": "next lint"
          },

          启动 server:

            yarn build && yarn dev

            访问 localhost:3000
            , 成功显示 Nextjs 首页就说明集成成功了。

            Nextjs 集成 fastify 不仅仅能够获得很好的性能提升,而且可以直接使用 fastify 的生态,比如解决跨域问题,需要代理 http api, 可以直接使用 fastify-http-proxy
             插件,虽然 Express 也有类似插件 http-proxy
            ,但是 fastify 的 http-proxy 要比 Express 的速度快 2~3倍。

            添加 http 代理包 fastify-http-proxy
            :

              yarn add fastify-http-proxy

              修改 server.js
               文件:

                const fastify = require('fastify')();
                const fastifyNext = require('fastify-nextjs');
                const httpProxy = require('fastify-http-proxy');


                fastify.register(httpProxy, {
                upstream: 'http://api.example.com',
                prefix: '/api',
                http2: false,
                })


                fastify.register(fastifyNext, {dev: false})
                .after(() => {
                fastify.next('/*')
                });


                fastify.listen(3000, err => {
                if (err) throw err;
                console.log('Server listening on http://localhost:3000')
                })

                访问 localhost:3000/api
                 就能获取对应站点信息。

                文章转载自程序猿研究所,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                评论