Last year I was obsessed with the stack below ๐ฅ
- Could Functions: For Node.js hosting
- Nuxt.js: For backend and frontend
- Firebase Hosting: For static files (HTML, CSS, JavaScript and etc)
- Cloudinary: For media files (dev.to uses this!)
When I first started using Nuxt.js with Cloud Functions, I could not understand how they communicate with each other.
How does Express call Nuxt.js when it receives a request?
So this time, I am going to elaborate on how we can connect Express to Nuxt.js on Cloud Functions.
Integrate Nuxt.js with Express
Point1. Use Nuxt.js as middleware on Express.
You can use Nuxt.js as middleware like this
I didn't have such an idea that I can use Nuxt.js as middleware on another framework.
Separate processing for each path using nuxt.renderRoute()
With nuxt.renderRoute(), you can decide which page component Nuxt.js will use for each path.
For example, the application is https://example.com
.
If you wrote the following, if you went to https://example.com
, you would see the Nuxt.js uses pages/top.vue
. Easy!!
app.get('/', (req, res) => {
nuxt.renderRoute('/top', { req })
.then(result => {
res.send(result.html);
})
.catch(e => {
res.send(e);
});
});
You cam pass the context as a second argument.
If you want to call some API on Express and pass the response to Nuxt.js, you can use req
object like below.
app.get('/', (req, res) => {
(async () => {
// Call an API with axios
const { data } = await axios.get('https://api.com');
req.data = data;
const result = await nuxt.renderRoute('/top', { req });
res.send(result.html);
})();
});
You can use that data with Nuxt.js asyncData
function.
<template>
<div>
{{ apiResult }}
</div>
</template>
<script>
export default {
asyncData(context) {
return { apiResult: context.req.data };
}
}
</script>
Explanation of the entire process with diagrams
- Client send a request to Firebase Cloud Functions (or any other web servers) and Express receive it.
- Express calls
nuxt.renderRoute()
- Nuxt.js generates HTML and returns it to Express
- Express sends the HTML returned by Nuxt.js to the client
Hope it helps!
Thank you for reading!!
Check my socials as wellโ๏ธ
Twitter: @askmakers_app
Product Hunt: @taishi_kato
I am currently looking for full-time job in Vancouver and Toronto area!
My resume is here.
Please hit me if you can help๐
Thank you!
Top comments (1)
Great post!
I'm curious about it:
How can I run dev server when using Nuxt.js as a middleware on Express? How to make sure nuxt-related bundles would watch file changes?