nuxt-http-status v1.0.3
Nuxt Http-Status Module
A Nuxt 3 module that integrates the http-status
package, making HTTP status codes and messages easily accessible both on client and server. This allows you to consistently reference codes and associated messages without needing to manually import http-status
in every file.
Features
- π¦ Easy Access to HTTP Status Codes: Provides a
$httpStatus
object via Nuxt's injection, so you can easily referencehttpStatus.OK
,httpStatus.NOT_FOUND
, etc. - π‘ Composable Integration: Use
useHttpStatus()
composable to access codes and messages in your Vue components without imports. - π Server-Side Context: Leverages a server handler to inject
httpStatus
intoevent.context
, letting you set status codes in your API endpoints without additional imports. - π TypeScript Support: Fully typed, improving DX with auto-completion and type hints.
Quick Setup
Install the module into your Nuxt application with:
npx nuxi module add nuxt-http-status
Or add it manually to your nuxt.config.ts
:
export default defineNuxtConfig({
modules: [
'nuxt-http-status'
]
})
Usage Examples
Client-Side (Components)
Within a *.vue
component, you can easily access HTTP status codes:
<script setup lang="ts">
const { OK, NOT_FOUND } = useHttpStatus()
console.log(OK) // 200
console.log(NOT_FOUND) // 404
// Fetch an API endpoint with a chosen status code
const response = await $fetch('/api/status?code=404')
console.log(response) // { message: 'Status code returned: 404', code: 404 }
</script>
<template>
<div>
<h2>HTTP Status Codes</h2>
<p>OK: {{ OK }}</p>
<p>NOT_FOUND: {{ NOT_FOUND }}</p>
</div>
</template>
Server-Side (API Routes)
In your server API routes (e.g., server/api/status.ts
), httpStatus
is available via event.context
:
Basic example
import { defineEventHandler } from 'h3'
export default defineEventHandler((event) => {
const { httpStatus } = event.context
event.node.res.statusCode = httpStatus.OK
return { message: httpStatus[`${httpStatus.OK}_MESSAGE`], code: httpStatus.OK }
})
So that you can try others.
import { defineEventHandler, getQuery } from 'h3'
export default defineEventHandler((event) => {
const { httpStatus } = event.context
const query = getQuery(event)
let code = parseInt((query.code as string) || '', 10)
if (isNaN(code) || !Object.values(httpStatus).includes(code)) {
code = httpStatus.OK
}
event.node.res.statusCode = code
return { message: `Status code returned: ${code}`, code }
})
No direct import httpStatus from 'http-status'
is needed hereβit's already injected!
Accessing Messages
http-status
also provides standard messages for each code, accessible via keys like 200_MESSAGE
or 404_MESSAGE
:
const status = useHttpStatus()
console.log(status['200_MESSAGE']) // "OK"
console.log(status['404_MESSAGE']) // "Not Found"
That's it! You can now use Nuxt-HTTP-Status in your Nuxt app β¨