These integration guides are not official documentation and the Strapi Support Team will not provide assistance with them.
What Is NodeJS?
NodeJS is a server-side JavaScript runtime built on Chrome's V8 JavaScript engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient for building scalable network applications. By integrating NodeJS with Strapi, you can use JavaScript for both frontend and backend development, creating a unified language experience across the entire stack.
Why Integrate NodeJS With Strapi
By integrating NodeJS with Strapi, you leverage the benefits of using Node.js to create a powerful combination for developing flexible, scalable digital experiences. The Strapi 5 features bring enhanced performance and improved developer experience, including support for TypeScript in Strapi 5, while Strapi Cloud offers a fully managed solution that eliminates infrastructure headaches.
Start with Strapi Cloud to experience the power when you integrate NodeJS with Strapi without infrastructure hassle.
API Flexibility
Strapi automatically creates RESTful APIs for each content type as soon as you define it, and will also create GraphQL APIs if the GraphQL plugin is installed. This GraphQL and REST integration means you can pick the right API style for your specific needs, cutting down development time and allowing for quick changes.
This dual support lets teams use REST when they want simplicity, or GraphQL when they need precise data fetching—all from the same Strapi backend.
Performance Benefits
Strapi and NodeJS together boost performance through:
- Optimized data transfer: GraphQL fetches exactly what you need, avoiding the common problems of getting too much or too little data—especially important for mobile apps.
- Reduced backend overhead: Since APIs are generated automatically, you write less code, resulting in a cleaner, faster backend.
- For high-traffic sites, implementing API request throttling can further enhance performance.
These performance gains really matter for high-traffic sites or content-heavy platforms where speed counts.
Scalability Advantages
Strapi's architecture, powered by NodeJS, makes scaling simple:
- Horizontal scaling is achieved by adding more servers when you need to handle more users.
- Additionally, you can add new features or content types without rebuilding everything, thanks to Strapi's flexible architecture.
Effective content lifecycle management is also facilitated by Strapi's scalable architecture.
Both REST and GraphQL APIs work independently, making your application easier to grow as your needs change.
Customizability
Strapi gives developers the flexibility they need:
- Add functionality through plugins
- Create a custom API endpoint in Strapi for your specific business needs
- Use the vast NodeJS ecosystem to enhance capabilities
By leveraging the Strapi middleware architecture, you can add custom integrations tailored to your requirements. With Strapi CMS for NodeJS, developers can build unique solutions without being boxed in by the CMS.
Integration Capabilities
With its NodeJS foundation, Strapi plays nicely with:
- Popular frontend frameworks (React, Vue, Angular)
- Existing NodeJS services and microservices
- Third-party tools and APIs
As a headless CMS with Strapi, this compatibility makes development smoother and helps create more connected applications. For example, you can easily add Google Maps integration to your Strapi application, leveraging the benefits of headless CMS for flexible content delivery across multiple channels.
By integrating NodeJS with Strapi, developers can create flexible, high-performance applications that scale and customize easily. Whether you're building a content-rich website, an eCommerce platform, or a multi-channel digital experience, this combination gives you the tools to bring your ideas to life.
Keep in touch with the latest Strapi and Node.js updates
How to Integrate and Deploy Strapi With NodeJS
Deploying Strapi on NodeJS isn't complicated, but it does require careful planning. Here's how to do it right.
Prerequisites and Environment Setup
Before starting, make sure you have:
- Node.js (LTS versions 18, 20, or 22 only—odd-numbered releases like 19, 21 are not supported)
- npm or yarn package manager
- Git for version control
- Python (not required for SQLite with Strapi)
For your database, choose from PostgreSQL, MySQL, SQLite, or others based on how much you need to scale.
Initial Project Setup
To create a new Strapi project, run:
1npx create-strapi-app my-project --quickstart
This command sets up a new Strapi project with default settings and starts the server. You'll be prompted to create your first administrator account through the admin panel.
Configuration for Development and Production
Good configuration makes deployment much easier:
- Set up environment variables in a
.env
file or your server configuration. Include database credentials, host settings, and other environment-specific options. - Create production-specific configurations in
config/env/production/
to override default settings. - Example production configuration:
1module.exports = ({ env }) => ({
2 host: env('HOST', '0.0.0.0'),
3 port: env.int('PORT', 1337),
4 // Add other production-specific settings
5});
Deployment Process to Integrate NodeJS With Strapi
1/. Build the admin UI:
1npm run build
2/. Start the server in production mode:
1NODE_ENV=production npm run start
For better process management, consider using PM2:
1pm2 start npm --name strapi -- run start
Depending on your needs, there are many Strapi deployment options available to help you deploy your application effectively.
Add API Request to Strapi
Once your Strapi application is deployed, you'll need to interact with it from your Node.js application. Here's how to make API requests to your Strapi backend:
1/. Using Axios for REST API calls:
1const axios = require('axios');
2
3// Fetching a list of products
4async function getProducts() {
5 try {
6 const response = await axios.get('http://your-strapi-url/api/products');
7 return response.data;
8 } catch (error) {
9 console.error('Error fetching products:', error);
10 throw error;
11 }
12}
13
14// Creating a new product
15async function createProduct(productData, token) {
16 try {
17 const response = await axios.post('http://your-strapi-url/api/products',
18 { data: productData },
19 {
20 headers: {
21 'Content-Type': 'application/json',
22 'Authorization': `Bearer ${token}`
23 }
24 }
25 );
26 return response.data;
27 } catch (error) {
28 console.error('Error creating product:', error);
29 throw error;
30 }
31}
2/. Using GraphQL with Strapi:
1const { request, gql } = require('graphql-request');
2
3const query = gql`
4 query {
5 products {
6 data {
7 id
8 attributes {
9 name
10 price
11 description
12 }
13 }
14 }
15 }
16`;
17
18async function fetchProductsWithGraphQL() {
19 try {
20 const data = await request('http://your-strapi-url/graphql', query);
21 return data.products;
22 } catch (error) {
23 console.error('Error fetching with GraphQL:', error);
24 throw error;
25 }
26}
Authentication
Strapi uses JWT (JSON Web Tokens) for authentication. Here's how to implement authentication in your Node.js application:
1/. User Registration:
1const axios = require('axios');
2
3async function registerUser(userData) {
4 try {
5 const response = await axios.post('http://your-strapi-url/api/auth/local/register', {
6 username: userData.username,
7 email: userData.email,
8 password: userData.password
9 });
10
11 return {
12 user: response.data.user,
13 jwt: response.data.jwt
14 };
15 } catch (error) {
16 console.error('Registration error:', error.response?.data || error);
17 throw error;
18 }
19}
2/. User Login:
1async function loginUser(credentials) {
2 try {
3 const response = await axios.post('http://your-strapi-url/api/auth/local', {
4 identifier: credentials.email, // can be email or username
5 password: credentials.password
6 });
7
8 return {
9 user: response.data.user,
10 jwt: response.data.jwt
11 };
12 } catch (error) {
13 console.error('Login error:', error.response?.data || error);
14 throw error;
15 }
16}
3/. Making Authenticated Requests:
1async function getUserProfile(userId, jwt) {
2 try {
3 const response = await axios.get(`http://your-strapi-url/api/users/${userId}`, {
4 headers: {
5 Authorization: `Bearer ${jwt}`
6 }
7 });
8
9 return response.data;
10 } catch (error) {
11 console.error('Error fetching user profile:', error);
12 throw error;
13 }
14}
Populating Strapi with Data
There are several approaches to populate your Strapi instance with initial data:
1/. Using Strapi's Content API:
1const axios = require('axios');
2const fs = require('fs');
3
4async function seedData(jwt) {
5 try {
6 // Read seed data from JSON file
7 const productsData = JSON.parse(fs.readFileSync('./seed-data/products.json', 'utf8'));
8
9 // Create each product
10 for (const product of productsData) {
11 await axios.post('http://your-strapi-url/api/products',
12 { data: product },
13 {
14 headers: {
15 'Content-Type': 'application/json',
16 'Authorization': `Bearer ${jwt}`
17 }
18 }
19 );
20 console.log(`Product ${product.name} created successfully`);
21 }
22
23 console.log('All seed data imported successfully');
24 } catch (error) {
25 console.error('Error seeding data:', error);
26 throw error;
27 }
28}
2/. Using Strapi's Seed Scripts:
Create a seed script in your Strapi project:
1// scripts/seed.js
2const fs = require('fs');
3const path = require('path');
4
5async function seedDatabase() {
6 try {
7 // Read seed data
8 const categoriesData = JSON.parse(
9 fs.readFileSync(path.resolve(__dirname, '../data/categories.json'), 'utf8')
10 );
11 const productsData = JSON.parse(
12 fs.readFileSync(path.resolve(__dirname, '../data/products.json'), 'utf8')
13 );
14
15 // Create categories first
16 for (const category of categoriesData) {
17 await strapi.entityService.create('api::category.category', {
18 data: category
19 });
20 }
21
22 // Then create products with categories
23 for (const product of productsData) {
24 await strapi.entityService.create('api::product.product', {
25 data: product
26 });
27 }
28
29 console.log('Seed completed successfully');
30 } catch (error) {
31 console.error('Seed error:', error);
32 }
33}
34
35module.exports = seedDatabase;
Run the script with:
1NODE_ENV=development node -e "require('./scripts/seed.js')()"
3/. Using Strapi's Database Lifecycles:
For more advanced seeding, you can use Strapi's lifecycle hooks in your models:
1// api/product/models/product.js
2module.exports = {
3 lifecycles: {
4 async beforeCreate(data) {
5 // Modify data before creation
6 if (data.autoGenerateSKU) {
7 data.sku = `PRD-${Math.floor(Math.random() * 10000)}`;
8 }
9 },
10 // Other lifecycle hooks
11 },
12};
Keep in touch with the latest Strapi and Node.js updates
Project Example of Integrating NodeJS With Strapi (+ Github Project Repo)
Let's explore how to combine Node.js with Strapi to build a dynamic product catalog for an e-commerce platform.
Project Overview
We're creating a flexible product catalog that's easy to manage through Strapi's admin interface and display on a React frontend. This setup uses Strapi for content management and Node.js for performance to deliver a fast, customizable solution.
Implementation Highlights
- API Design: We're using both RESTful and GraphQL APIs to show off Strapi's flexibility. The REST API is used for standard operations, while GraphQL tackles complex queries and real-time updates.
- Custom Fields: We've created custom fields for our product model, including options for variations like size and color.
- Media Management: We're using Strapi's built-in media library to handle product images efficiently.
- Node.js Backend Integration: We've added custom middleware to handle inventory checks and price calculations.
- React Frontend: A simple React app displays products by pulling data from the Strapi API.
Code Examples
Here's how we define our product model in Strapi:
1// api/product/models/product.js
2module.exports = {
3 attributes: {
4 name: {
5 type: 'string',
6 required: true
7 },
8 description: {
9 type: 'richtext'
10 },
11 price: {
12 type: 'decimal',
13 required: true
14 },
15 category: {
16 model: 'category'
17 },
18 images: {
19 collection: 'file',
20 via: 'related',
21 allowedTypes: ['images'],
22 plugin: 'upload',
23 required: false
24 },
25 variations: {
26 type: 'json'
27 }
28 }
29};
And here's an example of a custom middleware for inventory checking:
1// middleware/inventoryCheck.js
2module.exports = (strapi) => {
3 return {
4 initialize() {
5 strapi.app.use(async (ctx, next) => {
6 await next();
7 if (ctx.method === 'GET' && ctx.url.startsWith('/products')) {
8 const products = ctx.body.data || ctx.body;
9 for (let product of products) {
10 product.inStock = await checkInventory(product.id);
11 }
12 }
13 });
14 },
15 };
16};
17
18async function checkInventory(productId) {
19 // Implement inventory check logic here
20 return true; // Placeholder
21}
Note: The provided code for inventoryCheck.js needs to be updated to match Strapi's middleware structure. It should export a middleware function directly and be registered in the middleware configuration files for proper functionality.
Results and Benefits
By integrating NodeJS with Strapi for our product catalog, we've achieved:
- Improved Performance: Strapi's efficient content delivery and NodeJS's non-blocking I/O create faster response times, even under heavy load.
- Scalability: Our setup allows for easy horizontal scaling, with Strapi handling content and NodeJS managing business logic.
- Flexibility: Using both REST and GraphQL APIs gives us options for different frontend needs and third-party connections.
- Customization: We've extended Strapi's core functionality with custom middleware to fit specific business needs.
GitHub Repository
Check out the complete project on GitHub: Strapi-NodeJS Product Catalog
The repository includes:
- Strapi configuration files
- Custom API endpoints and middleware
- React frontend code
- Detailed setup instructions
This example shows how integrating NodeJS with Strapi creates a powerful backend for modern web applications. By using Strapi's content management and extending it with custom Node.js code, developers can quickly build scalable applications that handle complex business needs.
Strapi Open Office Hours
If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours Monday through Friday at 12:30 pm – 1:30 pm CST.
For more details, visit the Strapi documentation and Node.js documentation.