Search code examples
node.jsreactjsexpressnext.jsreact-fullstack

Api returning 404 on production


I have a next.js app and I'm trying to create an api. When I run it as development, the api's get called, but when I run it using next start I get a 404 error when calling the api's.

Here's the relevant server.js code:

app.prepare().then(() => {
    require('./server/startup/routes')(server);

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    const PORT = process.env.PORT || 5000;

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

Here's the routes file

module.exports = app => {
    app.use('/api/something-cool', cool);
};

Cool File:

const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {
    ...Code
    res.send({ status: 'ok' });
});

module.exports = router;

The api route of /something-cool works when I run nodemon, but when I run next run, it returns a 404 error. What am I doing wrong and how can I fix it?


Solution

  • You are using a custom server (express) on top of Next.js to customize routes. This means that first, you have to build the Next.js App and then you have to run your server.js file in order to serve the App.

    Option 1:

    Builds the production application first

    next build
    

    Then run you server.js file:

    NODE_ENV=production node server.js
    

    more info here https://github.com/zeit/next.js/tree/master/examples/custom-server-express

    Option 2:

    There is also the option to create the API route within the Next.js App without using a custom server.

    See https://github.com/zeit/next.js/tree/master/examples/api-routes for more info on how to do it.