Skip to content

Latest commit

 

History

History
72 lines (48 loc) · 1.75 KB

README.md

File metadata and controls

72 lines (48 loc) · 1.75 KB

💛 You can help the author become a full-time open-source maintainer by sponsoring him on GitHub.


vite-vercel

npm version npm downloads

Adding a middleware powered by Vercel Edge Function to your existing Vite project.

Install

npm i vite-vercel -D

Usage

In your vite.config.ts:

import { defineConfig } from "vite"
import vercel from "vite-vercel"

export default defineConfig({
  plugins: [
    vercel({
      middleware: "./middleware.ts",
    }),
  ],
})

Creating a middleware.ts:

import { MiddlewareRequest, MiddlewareResponse } from "vite-vercel/server"

export default (req: MiddlewareRequest) => {
  const url = new URL(req.url)

  if (url.pathname === "/from-middleware") {
    return new Response("from middleware")
  }

  // Rewrite to another URL
  if (url.pathname === "/todo") {
    return MiddlewareResponse.rewrite(
      "https://jsonplaceholder.typicode.com/todos/1",
    )
  }

  // Continue serving `index.html`
  return MiddlewareResponse.next()
}

Deploy on Vercel

This plugin uses Vercel's Build Output API (v3) which requires an Environment Variable named ENABLE_VC_BUILD to be set to 1 in order to enable the feature.

Credits

A lot of code are taken from Next.js since it's basically the same logic, all credits to Next.js authors.

Sponsors

sponsors

License

MIT © EGOIST