💛 You can help the author become a full-time open-source maintainer by sponsoring him on GitHub.
Adding a middleware powered by Vercel Edge Function to your existing Vite project.
npm i vite-vercel -D
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()
}
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.
A lot of code are taken from Next.js since it's basically the same logic, all credits to Next.js authors.
MIT © EGOIST