'How to build and start next.JS in production with graphql appollo server?
I am trying to dockerize a next.JS TypeScript app which uses express and apollo graphql.
My server/index.ts looks like this:
app.prepare().then(() => {
const server = express.default();
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
});
server.get("*", (req, res) => {
return handle(req, res);
});
apolloServer.start().then((res) => {
console.log(res);
const graphqlHandler = apolloServer.createHandler({ path: "/" });
server.use("/api/graphql", graphqlHandler);
server.listen(process.env.PORT || 3000, (err: string | void) => {
if (err) throw err;
console.log(
`>>> Listening on http://localhost:${process.env.PORT || 3000}`
);
});
});
});
apollo client:
const GRAPHQL_URL = process.env.NODE_ENV == 'development' ? 'http://localhost:3000/api/graphql': 'https://app1.com/api/graphql' ;
package.json:
"scripts": {
"build:next": "next build",
"build": "npm run build:next && npm run build:server",
"start": "next start",
"start:production": "node dist/index.js"
If building with npm run build and then npm run start:production, then after the first refresh I get the error ``` ReferenceError: Cannot access 'data' before initialization ````. In this case the query request is on the CSR and not with getServerSideProps. The environment variable here is still "development" and not "production".
If building with next build and next start then my appollo server does not start and I get a 404 that the graphql API is not found.
I am starting the app in production in a docker container:
FROM node:16
ENV PORT 3000
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Installing dependencies
COPY package*.json /usr/src/app/
RUN npm install
# Copying source files
COPY . /usr/src/app
# Building app
RUN npm run build
EXPOSE 3000
# Running the app
ENTRYPOINT [ "npm", "run", "start:production" ]
What am I doing wrong here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
