https://github.com/neo-ciber94/next-controllers
Api route controllers for NextJS
https://github.com/neo-ciber94/next-controllers
controller nextjs router
Last synced: 6 months ago
JSON representation
Api route controllers for NextJS
- Host: GitHub
- URL: https://github.com/neo-ciber94/next-controllers
- Owner: Neo-Ciber94
- License: mit
- Created: 2021-12-04T18:57:14.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-05-28T00:45:04.000Z (over 3 years ago)
- Last Synced: 2025-03-01T15:40:39.165Z (7 months ago)
- Topics: controller, nextjs, router
- Language: TypeScript
- Homepage:
- Size: 928 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Next-Controllers
A library for create api routes for `NextJS`.
## Installation
Install with `npm`
```codecopy
npm i next-controllers
```Or `yarn`
```codecopy
yarn add next-controllers
```## Setup
1. Enable decorators in your `tsconfig.ts`:
```json
{
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
```## Babel (Optional)
By default the `NextJS` will [detect the decorators](https://nextjs.org/docs/advanced-features/compiler#legacy-decorators) and use the ``SWC`` compiler to compile the code. In case of requiring `babel` you should also add this to enable the decorators:
1. Add or modify a `.babelrc` file with the following content:
```json
{
"presets": ["next/babel"],
"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }], "@babel/plugin-proposal-class-properties"]
}
```2. Install the `babel` dependencies
```codecopy
npm 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.
```ts
// pages/api/[...hello].tsimport { 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:**
```bash
curl http://localhost:3000/api
> Hello World!
``````bash
curl http://localhost:3000/api/Alexandra
> Hello Alexandra!
```