question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot reach API routes when using custom server

See original GitHub issue

Question about Next.js

I’ve set up a custom server.js, and also create an api as /pages/api/mock.ts.

The problem is, when I tried to fetch('api/mock'), I always got response with content OK instead of a JSON. But if I start Next app without custom server, api routes works as expected.

I cannot find examples for using API route with a custom server. Here’s my configuration:

In server.js

const Koa = require('koa');
const Router = require('koa-router');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 3000;
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
	const server = new Koa();
	const router = new Router();

	server.use(router.routes());

	/* some routes except `/api/` */

	router.get('*', async (ctx, next) => {
		await handle(ctx.req, ctx.res);
	});

	server.listen(port, err => {
		if (err) {
			throw err;
		}
		console.log(`> WEB Ready on http://localhost:${port}`);
	});
});

/pages/api/mock.ts

export default (_: NextApiRequest, res: NextApiResponse) => {
	// this will be triggered but it send 'OK' back instead of a JSON string
	console.log('hit');
	const mock = JSON.stringify({data: 'foo' });
	res.setHeader('Content-Type', 'application/json; charset=UTF-8');
	res.statusCode = 200;
	res.end(mock);
};

Reproduction

Please clone this repo: https://github.com/jesseminn/next-bug-demo

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
jesseminncommented, Aug 2, 2019

Found the solution. I think it’s because Koa has built-in response handling, and setting ctx.respond = false can bypass it. Check the official documentation about ctx.respond

app.prepare().then(() => {
	const server = new Koa();
	const router = new Router();

	server.use(router.routes());

	/* some routes except `/api/` */

	router.get('*', async (ctx, next) => {
		await handle(ctx.req, ctx.res);
		ctx.respond = false;
	});

	server.listen(port, err => {
		if (err) {
			throw err;
		}
		console.log(`> WEB Ready on http://localhost:${port}`);
	});
});
0reactions
balazsorban44commented, Jan 31, 2022

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot reach API routes when using custom server #8120
I cannot find examples for using API route with a custom server. Here's my configuration: In server.js. const Koa = require('koa'); ...
Read more >
Cannot GET api route (node.js, express) - Stack Overflow
I really suspect the issue is in the server.js, I tried messing around with it to no avail (feeding normalizePort() a string instead...
Read more >
Amazon EKS cluster endpoint access control
This topic helps you to enable private access for your Amazon EKS cluster's Kubernetes API server endpoint and limit, or completely disable, public...
Read more >
Deploying with Custom Serverless Next.js Routing - Vercel
This is an amazing feature of Next.js, however, it cannot control how the server routes to the app if the routes are not...
Read more >
API Routes: Introduction - Next.js
API routes provide a solution to build your API with Next.js. Any file inside the folder pages/api is mapped to /api/* and will...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found