This app is an example of how you can use Next.js API Routes as a back-end to your Next.js application.
Note: It is meant to be a reference project for my tests with other back-end solutions. Back-end implementation is naive and shouldn't be replicated in real apps. Front-end implementation, besides interactions with the back-end, doesn't matter much.
yarn
yarn prepare
yarn dev
Note: don't forget yarn prepare, as it will generate secrets for handling authentication.
I want to try and list the differences between major back-end solutions and how well they integrate with Next.js, to help fellow front-end developers choose the solution that best fits their next project. To do so, I will build a Cocktails app with different back-end solutions, and compare them all at the end. You can find the article here.
For the test to be relevant, the app should support the following features:
- Authentication (content will be protected behind authentication)
- List of cocktails (list querying), search by ingredient (search), and access a cocktail details (item querying)
- Like cocktails (simple write)
- Display a cocktail at random (custom logic)
The tools I am interested in testing should support all these use cases, and also a GraphQL interface and/or type generation from the database model.
At the end of the test, I will outline relevant differences between all the solutions tested.
Let's assume we have a Next.js project and all of the front-end bits are finished, as we are only interested in integrating the back-end. For this project, this step is this commit.
We will also assume prior knowledge of Express APIs, particularly how to handle requests.
We will use Next.js API routes, which are a built-in feature of Next.js projects, so we don't have anything more to configure.
Documentation: Next.js API routes
This API will be REST as it is only a reference for our future tests.
Steps:
- Create a
/pages/apifolder - For each request, create a
[requestName].tsfile in thepages/apifolder - Implement logic as you would in a regular Express app (examples here)
- Call the routes you have created in your React code, pointing to
/api/[requestName](example here)
That's it, you have your back-end!