阿里云主机折上折
  • 微信号
Current Site:Index > Custom middleware integration

Custom middleware integration

Author:Chuan Chen 阅读数:7993人阅读 分类: 构建工具

Project Configuration and Basic Usage

The Vite.js configuration file vite.config.js is located in the project root directory and defines build behavior by exporting an object. Basic configuration example:

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
    open: true
  },
  build: {
    outDir: 'dist',
    assetsDir: 'static'
  }
})

Common configuration items:

  • plugins: Array of plugins to use
  • server: Development server options
  • build: Production build options
  • resolve: Path resolution configuration
  • css: CSS-related configuration

Environment variables are managed via .env files, with mode differentiation support:

# .env.development
VITE_API_BASE=http://localhost:3000/api

# .env.production
VITE_API_BASE=https://api.example.com

Custom Middleware Integration

Vite's devServer is based on Connect middleware architecture and can be extended via the configureServer hook:

// vite.config.js
export default defineConfig({
  plugins: [{
    name: 'custom-middleware',
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        if (req.url === '/custom') {
          res.end('Hello from custom middleware!')
        } else {
          next()
        }
      })
    }
  }]
})

Common Middleware Scenarios

  1. API Proxy Middleware:
import proxy from 'http-proxy-middleware'

configureServer(server) {
  server.middlewares.use(
    '/api',
    proxy({
      target: 'http://localhost:4000',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/api/, '')
    })
  )
}
  1. Request Logging Middleware:
configureServer(server) {
  server.middlewares.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`)
    next()
  })
}
  1. Mock Data Middleware:
configureServer(server) {
  server.middlewares.use('/mock', (req, res) => {
    const data = {
      '/users': [{ id: 1, name: 'Alice' }],
      '/products': [{ id: 101, title: 'Vite Guide' }]
    }
    res.setHeader('Content-Type', 'application/json')
    res.end(JSON.stringify(data[req.path]))
  })
}

Advanced Middleware Patterns

Conditional Middleware Loading

configureServer(server) {
  if (process.env.NODE_ENV === 'development') {
    server.middlewares.use(require('vite-plugin-mock').createMockMiddleware())
  }
}

Middleware Execution Order Control

configureServer(server) {
  // First-executed middleware
  server.middlewares.use((req, res, next) => {
    req.startTime = Date.now()
    next()
  })

  // Last-executed middleware
  return () => {
    server.middlewares.use((req, res, next) => {
      console.log(`Request took ${Date.now() - req.startTime}ms`)
      next()
    })
  }
}

WebSocket Middleware Integration

configureServer(server) {
  const wss = new WebSocket.Server({ noServer: true })
  
  server.httpServer?.on('upgrade', (req, socket, head) => {
    if (req.url === '/ws') {
      wss.handleUpgrade(req, socket, head, (ws) => {
        wss.emit('connection', ws, req)
      })
    }
  })

  wss.on('connection', (ws) => {
    ws.send('Connected to Vite WS server')
  })
}

Plugin and Middleware Collaboration

Create custom plugins to integrate middleware logic:

// vite-plugin-custom.js
export default function customPlugin(options) {
  return {
    name: 'vite-plugin-custom',
    configureServer(server) {
      const middleware = createCustomMiddleware(options)
      server.middlewares.use(middleware)
    }
  }
}

function createCustomMiddleware(options) {
  return (req, res, next) => {
    // Custom logic
    if (req.headers['x-custom-header']) {
      res.setHeader('x-custom-response', 'processed')
    }
    next()
  }
}

Performance Optimization Middleware

Implement cache control and performance monitoring:

configureServer(server) {
  server.middlewares.use('/assets', (req, res, next) => {
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
    next()
  })

  server.middlewares.use((req, res, next) => {
    const timer = setTimeout(() => {
      console.warn(`Slow request: ${req.url}`)
    }, 2000)
    
    const originalEnd = res.end
    res.end = function(...args) {
      clearTimeout(timer)
      originalEnd.apply(this, args)
    }
    
    next()
  })
}

Security-Related Middleware

Enhance development environment security:

configureServer(server) {
  server.middlewares.use((req, res, next) => {
    // Set security headers
    res.setHeader('X-XSS-Protection', '1; mode=block')
    res.setHeader('X-Content-Type-Options', 'nosniff')
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin')
    
    // Block access to sensitive paths
    if (req.url.match(/\.(env|config|git)/i)) {
      res.statusCode = 403
      return res.end('Access denied')
    }
    
    next()
  })
}

Debugging and Error Handling

Middleware debugging techniques:

configureServer(server) {
  server.middlewares.use((req, res, next) => {
    try {
      // Business logic
      if (req.url.startsWith('/debug')) {
        console.log('Request headers:', req.headers)
      }
      next()
    } catch (err) {
      console.error('Middleware error:', err)
      res.statusCode = 500
      res.end('Internal Server Error')
    }
  })
}

Add error boundary middleware:

configureServer(server) {
  server.middlewares.use((err, req, res, next) => {
    if (err) {
      res.status(500).json({
        error: 'Middleware Error',
        message: err.message,
        stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
      })
    } else {
      next()
    }
  })
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.