首页 > 解决方案 > Running Express.js inside Next.js

问题描述

I'm trying to make Express running a neat way inside Next.js. As source of informations I used official documentation from Next.js website and their github repository about that topic

I succeed to make Express running, but I'm having bad development experience as every time I make changes inside files in my server directory, the server crashes and I've got this exception raised:

Error: Could not find a production build in the '/Users/******/******/nextjs-express/.next' directory. Try building your app with 'next build' before starting the production server. https://err.sh/vercel/next.js/production-start-no-build-id

****** personal path

So I've got to shut down the server, run npm run build and then restart the server with npm run server to apply changes without troubles. It's annoying. Here is my script in package.json for npm run server: nodemon --watch server server/index.js - as you see I'm using nodemon to watch every changes in my server directory.

1- So my first question is how can I apply changes to files inside my server directory without having to npm run build every time I change something?

2- My second question is about data fetching on client side. Below a random auth component for instance.

export default function AuthComponent() {
    const handleSignIn = async () => {
        try {
            const res = await fetch(
                `http://localhost:${process.env.PORT}/api/auth/signin`,
                {
                    method: 'GET',
                }
            )
            console.log(res)
        } catch (err) {
            console.log(`Error: ${err}`)
        }
    }

    return (
        <div>
            <button onClick={handleSignIn}>Sign in</button>
        </div>
    )
}

Inside fetch I've to hard code the server URL (port) like so (1) http://localhost:5000/api/auth/signin (I established my server on port 5000) but I would like this server URL to be (2) /api/auth/signin instead. If I leave the server URL like (2) I can't communicate with my backend as the URL remains localhost:3000, the Next.js default one. Furthermore, taking into account that I've got env variables (in a .env.local file) at the root of my project with one defining my server port (PORT=5000), I can't change (1) into http://localhost:${process.env.PORT}/api/auth/signin because I can't access env variables from client side. So my second question is how to establish my server entry point as /api (or / or whatever) and not http://localhost:5000/api (or whatever port) for client / browser?

Also you should know that I've written a proxy in my package.json like so "proxy": "http://127.0.0.1:5000" but this does not work.

标签: reactjsexpressnext.js

解决方案


推荐阅读