Skip to content

Instantly share code, notes, and snippets.

@davecarlson
Last active May 11, 2023 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davecarlson/868cb69f90dee58ec6dc41065b8ef2e8 to your computer and use it in GitHub Desktop.
Save davecarlson/868cb69f90dee58ec6dc41065b8ef2e8 to your computer and use it in GitHub Desktop.
Middleware Wrapper Function for Next.js Pages API Routes
/* Current Pages Directory Implementation */
// pages/api/test.ts
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
interface RequestWithDb extends NextApiRequest {
db: string;
}
const withDatabase =
(fn) => async (req: NextApiRequestWithDb, res: NextApiResponse, next: NextApiHandler) => {
req.db = "database"
return fn(req, res, next);
};
async function myApiHander(request: RequestWithDb, response: NextApiResponse ) {
console.log(request.db) // returns "database"
}
export default withDatabase(myApiHander)
/* This 'works' in apps route.js, but feels wrong */
// app/test/route.ts
import { NextResponse } from 'next/server'
export const GET = (request) => withDatabase(request, function(requestWithDb) {
console.log(requestWithDb)
return NextResponse.json({
status: 'ok', db: requestWithDb.db
})
})
const withDatabase = (req, fn) => {
req.db = 'database'
return fn(req)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment