Now I will make an example about CRUD ( create, read, update, delete ) in NextJS 13 . Share with everyone how to set up routes in NextJS 13, so we can configure paths to create, read, and edit in the application. Here I use the latest version of NextJS 13. For me, I already have a BackEnd, so in this article I will only do the frontend
- app/libs/index.ts : build the libraries you want
- app/types/index.ts : build the interfaces
- api /posts/route.ts : GET (Get a list of all posts), POST (Add a post)
- api/posts/[id]/route.ts : GET : get post via ID PUT : update post from ID DELETE : delete post from ID
- app/post/page.tsx : Display list of posts
- app/post/create/page.tsx : Form to add posts
- app/post/edit/[id]/page.tsx : Form to edit posts from ID
- app/post/read/[id]/page.tsx : Form to display posts from ID
- app/components/Header.ts : design header interface
- app/components/Post.ts : display post data
- app/layout.tsx : project layout interface
- app/page.tsx : home page interface
Demo:
Github : Building A Simple CRUD API With Next.Js 13
Okay let's start building a project
npx create-next-app@latest
If you have not seen the article on creating a NextJS project, please review this article: Create A Project With Next.Js
- app/libs/index.ts : The code below, we handle API requests
export const fetcher = (url: string) => fetch(url).then((res) => res.json());
- app/types/index.ts : set the properties of a Model, using the interface in typescript , need to configure properties of a certain data type
export interface UserModel{
id:number,
name:string,
}
export interface PostModel{
id:number,
title:string,
keyword:string,
des:string,
slug:string,
image:string,
publish:number,
content:string,
created_at:string
user:UserModel,
deletePost:(id: number)=> void;
}
export interface PostAddModel{
title:string,
content:string
}
- api/posts/route.ts : We need to build a route, to request Api, here we need to install 2 methods ( GET , POST )
import { NextRequest, NextResponse } from 'next/server'
export async function GET() {
const res = await fetch(process.env.PATH_URL_BACKEND+'/api/posts', {
headers: {
'Content-Type': 'application/json',
},
})
const result = await res.json()
return NextResponse.json({ result })
}
export async function POST(request: NextRequest) {
const body = await request.json()
const res = await fetch(process.env.PATH_URL_BACKEND+'/api/posts'
