この記事ではNuxt.jsのSSRで独自のミドルウエアを噛ませる方法について紹介します。
Nuxt.jsのserverMiddlewareを使う
Nuxt.jsの公式ドキュメントによるとNuxtは内部でエンジニアが独自で作ったミドルウエアを追加するためのconnect instanceを生成してくれます。これにより外部のサーバーを別途用意することなくミドルウエア認証を実装することができるようです。
Nuxt internally creates a connect instance that you can add your own custom middleware to. This allows us to register additional routes (typically /api routes) without need for an external server.
引用:「The serverMiddleware Property」
https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware
nuxt.config.jsに設定を追加する
ミドルウエアの設定は簡単で、nuxt.config.js
のserverMiddleware
に該当するミドルウエアのpathを設定してあげれば良いだけです。コードは公式サイトから持ってきたものです。
// nuxt.config.js
serverMiddleware: ['~/api/logger']
//api/logger.js
export default function (req, res, next) {
// req is the Node.js http request object
console.log(req.url)
// res is the Node.js http response object
// next is a function to call to invoke the next middleware
// Don't forget to call next at the end if your middleware is not an endpoint!
next()
}
これにより、ただURLをconsoleに吐くだけのミドルウエアを実装することができます。指定のエンドポイントを叩いたときのみミドルウエアの処理を噛ませたい時は次のようにpathを指定してあげればよいです。
// nuxt.config.js
// Will register file from project api directory to handle /api/* requires
{ path: '/api', handler: '~/api/index.js' },
以上で今回の記事は終了です。この記事が誰かの役に立てれば幸いです。
参考文献: