How to use stimulus js with express js-Fincode Fusion-techahmed

 In this blog we will see how can we use stimulus js with node js application

Intro to stimulus js:

Stimulus is a JavaScript framework with modest ambitions. It doesn’t seek to take over your entire front-end—in fact, it’s not concerned with rendering HTML at all. Instead, it’s designed to augment your HTML with just enough behavior to make it shine. Stimulus pairs beautifully with Turbo to provide a complete solution for fast, compelling applications with a minimal amount of effort.

A screenshot demonstrating how simple is to use stimulus


1. initialize a blank npm project directory
2. Create a server.js.
3. Run:

npm install express multer webpack webpack-dev-middleware helmet ejs cookie-parser csurf
3. Write following code in server.js
const path = require("path");
const express = require("express");
const multer  = require("multer");
const webpack = require("webpack");
const webpackMiddleware = require("webpack-dev-middleware");
const webpackConfig = require("./webpack.config");
const staticPath = path.join(__dirname, "static");
const port = process.env.PORT || 9000;
const app = express();
const upload = multer();
const helmet = require("helmet");
const ejs = require("ejs");
const cookieParser = require("cookie-parser");
const csrf = require("csurf");
const csrfProtection = csrf({ cookie: true });

app.use(helmet()); // basic web security headers

app.set("view engine", "ejs");

app.get("/", csrfProtection, (req, res) => {
  res.render("index", { csrfToken: req.csrfToken() });

// csrfProtection position requires formdata as it looks for body._csrf"/greet", upload.none(), csrfProtection, (req, res) => {
  if (!req.body) return res.sendStatus(400);
  const greeting = req.body["greeting"];
  const result = ejs.render("And <%= greeting %> to you!", {greeting: greeting});

app.listen(port, () => {
    console.log(`Listening on port ${port}`)


mkdir static views src src/controllers
5.create index.ejs in views folder and write code in it

<!doctype html>
    <meta charset="utf-8">
    <link rel="stylesheet" href="main.css">
    <script src="bundle.js" async></script>
    <!--Using a form container is optional (works without Javascript) using a div instead to wrap input will work -->
    <form data-controller="greet" action="/greet" method="post" enctype="multipart/form-data"
          data-action="greet#greeting" autocomplete="off">
        <label><input type="text" name="greeting">Enter Greeting</label>
        <input type="hidden" name="_csrf" value="<%= csrfToken %>"/>
        <output data-target="greet.result"></output>

7. Style it in your way add css file in static folder or you can use style tag
8. Now in src/index.js paste following for registering controllers automatically

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start();
const context = require.context("./controllers", true, /\.js$/);
9. Create src/controllers/greet_controller.js and paste following code in it
import { Controller } from "stimulus";

export default class extends Controller {

    static targets = ["result"]; // references resultTarget in scope

    greeting(event) {

        event.preventDefault(); // disable form submit

        const form = this.element;

        fetch(form.action, {
            method: 'post',
            body: new FormData(form) //
            .then(response => response.text())
            .then(text => this.result = text)
            .catch(error => console.error(error));

    set result(text) {
        this.resultTarget.innerHTML = `


`; } }

10. Create webpack.config.js in the root of folder
const path = require("path");

module.exports = {
  entry: {
    bundle: "./src/index.js"

  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "public")

  devtool: "source-map",

  module: {
    rules: [
        test: /\.js$/,
        exclude: [
        use: [
          { loader: "babel-loader" }

11. Now you can run it as normal node js project
12. If there is any errror or you can not undersatnd what i said you can clone this repo

13. You can also check the official docs of Stimulus js