【Nextjs】API Routes return 404 “This page could not be found”

When you add API Routes in Nextjs, the errorAPI Routes return 404 "This page could not be found"
occurred.

There must be a setting somewhere that causes a 404. So I followed it and came to the conclusion that it is set in next.config.js.

目次

The route set in API Routes is 404.

First, the current situation.
I added src/pages/api/test.ts, hit /api/test and expected JSON data to be returned, but got the default 404 page.

import type { NextApiRequest, NextApiResponse } from 'next'

type ResponseData = {
    message: string
}

export default function handler(
    req: NextApiRequest,
    res: NextApiResponse<ResponseData>
) {
    res.status(200).json({ message: 'Hello from Next.js!' })
}

Click here for the official API Routes.

Resolved by modifying next.config.js

The problem was that only page.tsx was defined in pageExtensions in next.config.js.

module.exports = {
  pageExtensions: ["page.tsx"]
}

In this case, the ts files were also covered, so the following changes were made to address this issue.

module.exports = {
  pageExtensions: ["page.tsx", "api.ts"]
}

The api file was also changed to src/pages/api/test.api.ts and the API Routes configuration was completed.

よかったらシェアしてね!
目次