Last active
May 11, 2023 09:22
-
-
Save davecarlson/868cb69f90dee58ec6dc41065b8ef2e8 to your computer and use it in GitHub Desktop.
Middleware Wrapper Function for Next.js Pages API Routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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