Nuxt2でページ遷移制御(middleware)

ページコンポーネントに指定

export default defineComponent({
  middleware({ route, from, redirect }){
    if(route.name === 'application-id-confirm'){
      if(!from || from.name !== 'application-id-edit'){
        redirect({
            name: "application-id-edit",
            params: route.params,
        })
      }
    }
  },
});

Vue2+Compsition API の場合、 defineComponent 直下に beforeRouteUpdate などを指定できたが、SSR のときに動作しなかったので、↑の書き方に。

middleware が受け取れる context は公式を確認。
fromはクライアントでしか受け取れない

nuxt.config.js で target が server でないと、redirect した後に status が空になってしまう。

グローバルで指定(nuxt.config.jsで指定)

middleware/stats.ts

import { Context } from '@nuxt/types'
export default ({ route, from, redirect }:Context) => {
  if(route.name === 'application-id-confirm'){
    if(!from || from.name !== 'application-id-edit'){
      redirect({
          name: "application-id-edit",
          params: route.params,
      })
    }
  }
}

nuxt.config.js

export default {
  router: {
    middleware: ['stats'],
  },
}