next-controllers
v0.1.17
Published
An api for create routing controllers in nextjs
Downloads
4
Maintainers
Readme
Next-Controllers
A library for create api routes for NextJS
.
Installation
Install with npm
npm i next-controllers
Or yarn
yarn add next-controllers
Setup
Enable decorators in your
tsconfig.ts
:{ "experimentalDecorators": true, "emitDecoratorMetadata": true }
Add or modify a
.babelrc
file with the following content:{ "presets": ["next/babel"], "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }], "@babel/plugin-proposal-class-properties"] }
Install the
babel
dependenciesnpm i -D @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators
Usage
Create a file under pages/api/
with the pattern: [[...params]]
to allow catch all the request.
Define the controller on the route.
// pages/api/[...hello].ts
import { Get, NextApiContext, withController } from 'next-controllers';
class HelloController {
@Get()
sayHello() {
return 'Hello World!';
}
@Get('/:name')
sayHelloTo(context: NextApiContext) {
return `Hello ${context.request.params.name}!`;
}
}
export default withController(HelloController);
Request results:
curl http://localhost:3000/api
> Hello World!
curl http://localhost:3000/api/Alexandra
> Hello Alexandra!