Building a Next.js App with an AdonisJS API

Connect a Next.js front end to an AdonisJS V5 REST API.

In Building an API with AdonisJS V5 we built a small posts API with full CRUD routes and validation. Now we need a front end to use it. Next.js is a great fit because it can fetch data on the server before a page renders and still make requests from the browser.

Let's build out a Next.js 10 app that lists posts, shows a single post and creates new posts with a form.

Step 1: Create the Next.js app

npx create-next-app my-blog
cd my-blog
npm run dev

The app runs on http://localhost:3000. Keep the Adonis API running on http://localhost:3333 in another terminal with node ace serve --watch.

Step 2: Enable CORS in Adonis

The browser blocks requests from one origin (localhost:3000) to another (localhost:3333) unless the API says it's allowed. Adonis comes with CORS support built in, it's just turned off. Open config/cors.ts in the Adonis project and update these two options:

// config/cors.ts
const corsConfig: CorsConfig = {
enabled: true,
origin: ["http://localhost:3000"],
...
}

enabled turns the CORS middleware on and origin is the list of front ends allowed to call the API. Add your production URL here when you deploy.

Step 3: Add the API URL as an environment variable

Create a .env.local file at the root of the Next.js project:

NEXT_PUBLIC_API_URL=http://localhost:3333

The NEXT_PUBLIC_ prefix makes the variable available in the browser as well as on the server. We need that because the form will post from the browser. Restart npm run dev after adding it so Next.js picks it up.

Step 4: List the posts

getServerSideProps runs on the server on every request, so the page is rendered with the posts already in it:

// pages/index.js
import Link from "next/link"
export default function Home({ posts }) {
return (
<main>
<h1>Posts</h1>
<Link href="/posts/new">
<a>New post</a>
</Link>
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/posts/${post.id}`}>
<a>{post.title}</a>
</Link>
</li>
))}
</ul>
</main>
)
}
export async function getServerSideProps() {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/posts`)
const posts = await res.json()
return { props: { posts } }
}

Next.js makes fetch available on the server, so there's nothing to install. Notice this request comes from the Next.js server, not the browser, so CORS doesn't apply to it.

Step 5: Show a single post

Wrapping the file name in square brackets creates a dynamic route. Visiting /posts/1 gives us params.id of "1":

// pages/posts/[id].js
export default function Post({ post }) {
return (
<article>
<h1>{post.title}</h1>
<p>{post.body}</p>
</article>
)
}
export async function getServerSideProps({ params }) {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/posts/${params.id}`
)
if (!res.ok) {
return { notFound: true }
}
const post = await res.json()
return { props: { post } }
}

Our Adonis controller uses findOrFail, so a missing post responds with a 404. Returning notFound: true (new in Next.js 10) shows the Next.js 404 page in that case.

Step 6: Create a post from a form

The form runs in the browser, so this is the request that needs CORS:

// pages/posts/new.js
import { useState } from "react"
import { useRouter } from "next/router"
export default function NewPost() {
const router = useRouter()
const [title, setTitle] = useState("")
const [body, setBody] = useState("")
const [errors, setErrors] = useState([])
const handleSubmit = async (event) => {
event.preventDefault()
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/posts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ title, body }),
})
const data = await res.json()
if (!res.ok) {
setErrors(data.errors)
return
}
router.push(`/posts/${data.id}`)
}
return (
<form onSubmit={handleSubmit}>
<h1>New post</h1>
{errors.map((error) => (
<p key={error.field}>{error.message}</p>
))}
<label htmlFor="title">Title</label>
<input
id="title"
value={title}
onChange={(event) => setTitle(event.target.value)}
/>
<label htmlFor="body">Body</label>
<textarea
id="body"
value={body}
onChange={(event) => setBody(event.target.value)}
/>
<button type="submit">Save</button>
</form>
)
}

On success Adonis responds with the new post, so we can send the user straight to its page with router.push. If validation fails the API responds with a 422 and an errors array, and we show each message above the form.

Note: Sending Content-Type: application/json makes the browser send a CORS preflight OPTIONS request first. Adonis handles this for us once CORS is enabled.

Now visiting http://localhost:3000/posts/new, filling out the form and clicking Save will create the post and redirect to it. Heading back to the home page will show it in the list.

Summary

The Adonis API handles the data and validation, and Next.js renders the pages with getServerSideProps and sends new posts from the browser with fetch. Keeping them as two projects means you can deploy and scale each one on its own.

Have some feedback on this post? .