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

fix(nuxt): allow abortMiddleware to receive a nuxt error or error options #7335

Merged
merged 2 commits into from
Sep 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/nuxt/src/app/composables/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getCurrentInstance, inject } from 'vue'
import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router'
import { sendRedirect } from 'h3'
import { hasProtocol, joinURL, parseURL } from 'ufo'
import { useNuxtApp, useRuntimeConfig, useState } from '#app'
import { useNuxtApp, useRuntimeConfig, useState, createError, NuxtError } from '#app'

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

/** This will abort navigation within a Nuxt route middleware handler. */
export const abortNavigation = (err?: Error | string) => {
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 err instanceof Error ? err : new Error(err)
throw createError(err)
}
return false
}
Expand Down
9 changes: 9 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,15 @@ describe('middlewares', () => {
expect(html).toContain('Hello Nuxt 3!')
})

it('should allow aborting navigation on server-side', async () => {
const res = await fetch('/?abort', {
headers: {
accept: 'application/json'
}
})
expect(res.status).toEqual(401)
})

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

Expand Down
7 changes: 7 additions & 0 deletions test/fixtures/basic/middleware/abort.global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default defineNuxtRouteMiddleware((to) => {
if ('abort' in to.query) {
return abortNavigation({
statusCode: 401
})
}
})