5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt で router.beforeEach 内に next()を 使うと 404 になる件

Last updated at Posted at 2020-07-10

結論

In nuxt.js, we do some special stuff before mounting the app in SPA mode, so some things differs, also, we don't recommend to use router.beforeEach and using next because of our internal logic with fetch/asyncData.

You can do the same behaviour with the nuxt middleware.

Nuxtではrouter.beforeEachのなかでnext()使うのは推奨してないよ
nuxt.configのrouterプロパティで設定できるmiddlewareを使うといいよ、ハハッ

※hada の主観による意訳です

発端

local storage に持ってるユーザー情報が古い場合は update するみたいな処理を plugin のapp.router.beforeEach内で実装してると、なんか 404(This page could not be found) が出てくる

元のコード

まんまではないですが

plugins/router.ts
export default function ({ app, store }: Context): void {
  await app.router.beforeEach(async (to: Route, from: Route, next) => {
    // local storageにある特定のプロパティの値が1時間以上立っている場合はステータスをapiから取得し更新する的なサムシング
    if(moment(localDateTime).diff(lastUpdatedAt, 'hours') <= 1) {
      next()
      return
    }

    await updateUserStatus()
  }
}

やったこと

plugin で router.beforeEach してたのを、nuxt config の router に middleware 設定する方法に変更した

具体的には

  • router.beforeEach 内で next を使うのをやめる
  • router.beforeEach でやってた処理をミドルウェアにする
  • nuxt.config.ts にてミドルウェアを設定する
middleware/update-status.ts
export default async function ({ app, store }: Context): Promise<void> {
  if (moment(localDateTime).diff(lastUpdatedAt, "hours") <= 1) {
    return;
  }

  await updateUserStatus();
}
nuxt.config.ts
const nuxtConfig: Configuration = {
  // ...

  router: {
    middleware: ["update-status"],
  },
};
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?