Mike K
Mike K

Reputation: 6481

NextJS throwing 404 when deployed to Vercel

I have a custom express server that I'm using with NextJS.

Everything works just fine when I'm developing locally, but when I deploy to Vercel, I catch 404s whenever I try to access my backend API.

What could be going wrong? Here's my server.ts:

import express from 'express';
import next from 'next';
import bodyParser from 'body-parser';
import { connectDbs } from './config/db';
import { listingsRouter } from './routes';

const PORT = process.env.PORT || 3003;
const dbs = ['mydb'];

const dev = process.env.NODE_DEV !== 'production';
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();

const applyMiddleware = (app) => {
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
};

const applyRoutes = (app) => {
    app.use('/api/listings', listingsRouter);
};

const startServer = async () => {
    await nextApp.prepare();
    const app = express();

    applyMiddleware(app);
    applyRoutes(app);

    app.get('*', (req, res) => handle(req, res));

    await connectDbs(dbs);

    app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
};

startServer();

Upvotes: 2

Views: 3164

Answers (1)

styfle
styfle

Reputation: 24610

The Next.js documentation for custom servers:

A custom server cannot be deployed on Vercel, the platform Next.js was made for.

Source: Custom Server

Even though you can't deploy a custom server, you generally don't need to do so because Next.js supports Serverless Functions using the /pages/api directory.

Source: API Routes

Also take a look at this Guide explaining how to convert custom Next.js server to routes:

Source: Server to Routes Guide

Upvotes: 1

Related Questions