Skip to main content

PKU685: Middleware Handler Invalid

Error Message

[PKU685] Handler for pikkuMiddleware is not a function.

What Went Wrong

You're trying to register middleware, but the provided handler is not a valid function. Middleware must be wrapped with pikkuMiddleware().

How to Fix

Use pikkuMiddleware to define your middleware:

import { pikkuMiddleware } from '#pikku'

// ✅ Correct: Valid middleware
export const logRequest = pikkuMiddleware(async (ctx, next) => {
console.log(`Request: ${ctx.method} ${ctx.path}`)
return await next()
})

Then use it in your routes:

import { wireHTTP } from '@pikku/core/http'
import { myHandler } from './handlers'
import { logRequest } from './middleware'

wireHTTP({
method: 'post',
route: '/api/users',
func: myHandler,
middleware: [logRequest], // Apply middleware
})

Middleware Factory Pattern

For parameterized middleware, use pikkuMiddlewareFactory:

import { pikkuMiddlewareFactory } from '#pikku'

// Factory that creates middleware
export const rateLimiter = pikkuMiddlewareFactory((limit: number) => {
return pikkuMiddleware(async (ctx, next) => {
// Check rate limit
if (requestCount > limit) {
throw new Error('Rate limit exceeded')
}
return await next()
})
})

// Usage
wireHTTP({
method: 'post',
route: '/api/data',
func: myHandler,
middleware: [rateLimiter(100)], // Create middleware with parameter
})

Common Patterns

Logging Middleware

export const logger = pikkuMiddleware(async (ctx, next) => {
const start = Date.now()
const result = await next()
const duration = Date.now() - start
console.log(`${ctx.method} ${ctx.path} - ${duration}ms`)
return result
})

Authentication Middleware

export const requireAuth = pikkuMiddleware(async (ctx, next) => {
if (!ctx.session?.userId) {
throw new Error('Unauthorized')
}
return await next()
})

Error Handling Middleware

export const errorHandler = pikkuMiddleware(async (ctx, next) => {
try {
return await next()
} catch (error) {
console.error('Request failed:', error)
throw error
}
})

Common Mistakes

  • Using a regular function instead of pikkuMiddleware
  • Forgetting to call next()
  • Not returning the result from next()
  • Providing null or undefined as middleware
  • PKU835 - Permission Handler Invalid