Created
August 18, 2018 19:44
-
-
Save lorefnon/65b50deebef37228416331234885cde6 to your computer and use it in GitHub Desktop.
Integrating next.js, Apollo Server and Koa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"main": "server/index.js", | |
"scripts": { | |
"dev": "nodemon --watch server server/index.js", | |
"build": "next build", | |
"start": "NODE_ENV=production node server/index.js" | |
}, | |
"dependencies": { | |
"apollo-boost": "^0.1.13", | |
"apollo-server": "^2.0.4", | |
"apollo-server-koa": "^2.0.0-rc.12", | |
"graphql": "^0.13.0", | |
"koa": "^2.5.2", | |
"koa-graphiql": "^1.1.0", | |
"koa-router": "^7.4.0", | |
}, | |
"devDependencies": { | |
"nodemon": "^1.18.3" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Koa = require("koa"); | |
const next = require("next"); | |
const Router = require("koa-router"); | |
const { ApolloServer, gql } = require("apollo-server-koa"); | |
const graphiql = require("koa-graphiql").default; | |
const schema = gql` | |
type Query { | |
// TODO: Update | |
} | |
type Mutation { | |
// TODO: Update | |
} | |
` | |
const port = parseInt(process.env.PORT, 10) || 3000; | |
const dev = process.env.NODE_ENV !== "production"; | |
const app = next({ dev }); | |
const handle = app.getRequestHandler(); | |
const graphQLServer = new ApolloServer({ | |
typeDefs: schema, | |
resolvers: { | |
Query: { /* ... TODO: Add query resolvers here ... */ }, | |
Mutation: { /* ... TODO: Add mutation resolvers here ... */ } | |
}, | |
// Make graphql playgroud available at /graphql | |
playground: { | |
endpoint: "/graphql" | |
}, | |
bodyParser: true | |
}); | |
app.prepare().then(() => { | |
const server = new Koa(); | |
const router = new Router(); | |
graphQLServer.applyMiddleware({ | |
app: server | |
}); | |
// If you prefer graphiql over graphql playground | |
router.get( | |
"/graphiql", | |
graphiql(async ctx => ({ | |
url: "/graphql" | |
})) | |
); | |
router.get("*", async ctx => { | |
if (!ctx.path.match(/graphql/)) { | |
await handle(ctx.req, ctx.res); | |
ctx.respond = false; | |
} | |
}); | |
server.use(router.routes()); | |
server.listen(port, () => { | |
console.log(`> Ready on http://localhost:${port}`); | |
console.log(`> GraphiQL IDE available on http://localhost:${port}/graphiql`); | |
console.log(`> GraphQL Server (And GraphQL Playground) ready at http://localhost:${port}${graphQLServer.graphqlPath}`); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I love this! Thanks for the starting code