This package exports some common Next.js API middleware patterns that you might need across different applications. It aims to provide useful and mostly flexible drop-in functions.
If you have something in mind that is generally help- or useful and is not included in this list, please feel free to open an issue.
yarn add nextjs-api-common-middleware
npm install --save nextjs-api-common-middleware
While generally not required, it is recommended that you re-export the middleware collection with your own default configuration.
Create a file called middleware.js
/middleware.ts
somewhere that suits you well, the contents of the file should look something like this:
import { createExport } from 'nextjs-api-common-middleware';
const m = createExport({
catch: (_req, res, err) => {
console.error(err);
res.status(500).send('An unknown error occurred');
},
auth: {
strategy: 'custom',
custom: (authHeaderValue, _req) => {
if (authHeaderValue && authHeaderValue === 'test') {
return {
uid: 123,
user: {
firstname: 'Test',
lastname: 'User',
},
};
}
return null;
},
},
});
export default m;
// src/pages/api/hello.js
import m from '../../middleware'; // or 'nextjs-api-common-middleware'
async function handler(req, res) {
res.json({ hello: 'world' });
}
export default m.auth(handler); // second argument could be additional options
// src/pages/api/hello.js
import m from '../../middleware'; // or 'nextjs-api-common-middleware'
async function handler(req, res) {
res.json({ hello: 'world' });
}
export default m._.chain([m.auth, m.guard], handler, {
// auth options are still remembered from the initial configuration
guard: {
required: ['foo'],
},
});
Generated using TypeDoc