Because you could doesn’t mean you should series #2: Using the Connect app of Nuxt.js

Steve “Stefan” Fan
Jun 5 · 2 min read

(Note: this is part the salvation of my old blog, that a catastrophic event has recently happened me, I’m very sad now, and I will make an postmortem later)

I kind of like Nuxt.JS.

Despite it being kind of mediocre in architecture, and in each update it always break my app, I still think it is the authentic answer of Vue to Next.JS in the React land.

It has a lot of plugins, asynchronous loading and modules…The only thing I missed is a server backend to handle business logic.

Yet, universal application didn’t account for this and forces you to separate it into another domain, I know it has a good intention but this is kind of fussing for me. Did this mean I have to separately start two different Node applications at once?

Fortunately, with this trick the server-side render server can be exploited to add the things you wanted — Using the hook property in Nuxt!
In your nuxt.config.js, add the following thing:

export const hooks = {
// Write your hooks here
}

We will find the hook we need. According to @nuxt/server, this is what we wanted:

...
async setupMiddleware() {
// Apply setupMiddleware from modules first
await this.nuxt.callHook('render:setupMiddleware', this.app)
...

And this means we need to add a hook to setupMiddleware in the render namespace:

export const hooks = {
render: {
async setupMiddleware (app: any): Promise<void> {
// Do anything here...
}
}
}

And tada! You have full access to the underlying connect instance of Nuxt.JS. You can prompt to use apollo-server-express to attach an ad-hoc GraphQL server for testing!

export const hooks = {
render: {
async setupMiddleware (app: any): Promise<void> {
// Do anything here...
const schema = makeExecutableSchema({ ... })
server = new ApolloServer({ schema })
server.applyMiddleware({ app })
}
}
}

If you need WebSocket subscription support, you will also need to hook listen event as well:

export const hooks = {  
listen (httpServer: any): any {
server.installSubscriptionHandlers(httpServer)
},

This way you won’t get the 503 error since Apollo requires the created HTTP server instance to attach the actual WebSocket listener, not from the Express/Connect instance.

(Originally Published Date: 2019–02–02T12:14:39.044Z)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade