Nuxt.js middlewareの簡単な使い方

Nuxt.js middlewareの簡単な使い方

middolewareを利用するとレンダリングが実行される前に、処理を記述することが可能で、また、共通処理も記述することが可能です。

環境

  • OS  Ubuntu19.10
  • node v12.13.0
  • npm 6.12.1
  • Nuxt.js v2.10.2

nuxtインストール

nuxt-testという名前でプロジェクトを作成

 npx create-nuxt-app nuxt-test

<出力結果>
✨  Generating Nuxt.js project in nuxt-test
? Project name nuxt-test
? Project description My glorious Nuxt.js project
? Author name taro
? Choose the package manager Yarn
? Choose UI framework None
? Choose custom server framework None (Recommended)
? Choose Nuxt.js modules (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Choose linting tools (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Choose test framework None
? Choose rendering mode Universal (SSR)
? Choose development tools (Press <space> to select, <a> to toggle all, <i> to invert selection)

middleware利用

middlewareディレクトリ配下にtest.jsを下記のコードで作成します

export default function() {
    console.log("test middleware")
}

nuxt.config.jsに下記のコードを追加します。

router: {
    middleware: "test"
},

yarn devで起動すると、test middlewareと表示されることが確認できます。

pages配下にtest.vueという適当なファイルを作成して、ブラウザから http://localhost:3000 にアクセスにアクセスすると、同様にコンソールに「test middleware」と表示されることが確認できます。