Skip to content

Commit

Permalink
fix(nuxt): show error page after fatal abortNavigation (#21047)
Browse files Browse the repository at this point in the history
  • Loading branch information
xanderbarkhatov committed May 25, 2023
1 parent 4e6369c commit e50cabf
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
14 changes: 10 additions & 4 deletions packages/nuxt/src/app/composables/router.ts
Expand Up @@ -6,7 +6,7 @@ import { hasProtocol, joinURL, parseURL } from 'ufo'

import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import type { NuxtError } from './error'
import { createError } from './error'
import { createError, showError } from './error'
import { useState } from './state'

import type { PageMeta } from '#app'
Expand Down Expand Up @@ -155,10 +155,16 @@ export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
}
if (err) {
throw createError(err)

if (!err) { return false }

err = createError(err)

if (err.fatal) {
useNuxtApp().runWithContext(() => showError(err as NuxtError))
}
return false

throw err
}

export const setPageLayout = (layout: string) => {
Expand Down
8 changes: 8 additions & 0 deletions test/basic.test.ts
Expand Up @@ -710,6 +710,14 @@ describe('middlewares', () => {
expect(res.status).toEqual(401)
})

it('should allow aborting navigation fatally on client-side', async () => {
const html = await $fetch('/middleware-abort')
expect(html).not.toContain('This is the error page')
const page = await createPage('/middleware-abort')
await page.waitForLoadState('networkidle')
expect(await page.innerHTML('body')).toContain('This is the error page')
})

it('should inject auth', async () => {
const html = await $fetch('/auth')

Expand Down
18 changes: 18 additions & 0 deletions test/fixtures/basic/pages/middleware-abort.vue
@@ -0,0 +1,18 @@
<script setup lang="ts">
definePageMeta({
middleware: () => {
if (process.server || useNuxtApp().isHydrating) { return }
return abortNavigation({
fatal: true
})
}
})
const router = useRouter()
onNuxtReady(() => router.push({ path: '/middleware-abort', force: true }))
</script>

<template>
<div>
<!-- -->
</div>
</template>

0 comments on commit e50cabf

Please sign in to comment.