Skip to content
This repository was archived by the owner on Apr 6, 2023. It is now read-only.

Commit 9c3bef4

Browse files
authored
fix(nuxt): allow abortMiddleware to receive a nuxt error or error options (#7335)
1 parent 849b8cb commit 9c3bef4

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

packages/nuxt/src/app/composables/router.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { getCurrentInstance, inject } from 'vue'
22
import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router'
33
import { sendRedirect } from 'h3'
44
import { hasProtocol, joinURL, parseURL } from 'ufo'
5-
import { useNuxtApp, useRuntimeConfig, useState } from '#app'
5+
import { useNuxtApp, useRuntimeConfig, useState, createError, NuxtError } from '#app'
66

77
export const useRouter = () => {
88
return useNuxtApp()?.$router as Router
@@ -105,12 +105,12 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na
105105
}
106106

107107
/** This will abort navigation within a Nuxt route middleware handler. */
108-
export const abortNavigation = (err?: Error | string) => {
108+
export const abortNavigation = (err?: string | Partial<NuxtError>) => {
109109
if (process.dev && !isProcessingMiddleware()) {
110110
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
111111
}
112112
if (err) {
113-
throw err instanceof Error ? err : new Error(err)
113+
throw createError(err)
114114
}
115115
return false
116116
}

test/basic.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,15 @@ describe('middlewares', () => {
236236
expect(html).toContain('Hello Nuxt 3!')
237237
})
238238

239+
it('should allow aborting navigation on server-side', async () => {
240+
const res = await fetch('/?abort', {
241+
headers: {
242+
accept: 'application/json'
243+
}
244+
})
245+
expect(res.status).toEqual(401)
246+
})
247+
239248
it('should inject auth', async () => {
240249
const html = await $fetch('/auth')
241250

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export default defineNuxtRouteMiddleware((to) => {
2+
if ('abort' in to.query) {
3+
return abortNavigation({
4+
statusCode: 401
5+
})
6+
}
7+
})

0 commit comments

Comments
 (0)