As a Next.js user, one of the things I've been used to working with were built-in API routes. When I tried out Nuxt, I was curious how I would achieve the same functionality.
In this post, I'll walk through how to easily create API routes in a Nuxt app using Express.
Implementation
To get started, start with an existing Nuxt app or create a new one using npx:
npx create-nuxt-app nuxt-with-api
cd nuxt-with-api
Next, install express:
npm install express
Next, update nuxt.config.js
to add the following serverMiddleware
configuration to specify the directory of the API routes:
serverMiddleware: {
'/api': '~/api'
}
Next, create a folder called api., and within the api folder create a file called index.js and a file called hello.js:
Next, open api/index.js and add the following code to configure the entry point to the express server:
const express = require('express')
const app = express()
const hello = require('./hello')
app.use(hello)
if (require.main === module) {
const port = 3001
app.listen(port, () => {
console.log(`API server listening on port ${port}`)
})
}
module.exports = app
Next, open api/hello.js and add the following code to create a /hello
route:
const { Router } = require('express')
const router = Router()
router.use('/hello', (req, res) => {
res.end('Hello world!')
})
module.exports = router
Next, test it out by running npm run dev
.
Now, navigate to http://localhost:3000/api/hello
and you should see your API response!
Conclusion
Creating API routes in a Nuxt app is more work than with Next.js, but servermiddleware allows you to implement your own API route setup fairly easily.
Cover image by Diego PH
Top comments (3)
Would you explain the
if
block inindex.js
? Thanks.I think you meant
res.send('Hello world!')
, notres.end
Also, please explain what the
if (require.main === module)
statement is for. I've never seen that in ExpressJS. Thanks.works! but, when im deploying to vercel, im getting
502: BAD_GATEWAY
Code: NO_RESPONSE_FROM_FUNCTION
can you helpme?