Thursday, March 21, 2024

Construct a Full-stack App with Node.js and htmx — SitePoint

Must read


On this tutorial, I’ll show the best way to construct a completely functioning CRUD app utilizing Node for the backend and htmx for the frontend. This may show how htmx integrates right into a full-stack utility, permitting you to evaluate its effectiveness and determine if it’s a sensible choice to your future initiatives.

htmx is a contemporary JavaScript library designed to boost internet functions by enabling partial HTML updates with out the necessity for full web page reloads. It does this by sending HTML over the wire, versus the JSON payload related to conventional frontend frameworks.

What We’ll Be Constructing

We’ll develop a easy contact supervisor able to all CRUD actions: creating, studying, updating, and deleting contacts. By leveraging htmx, the applying will supply a single-page utility (SPA) really feel, enhancing interactivity and person expertise.

If customers have JavaScript disabled, the app will work with full-page refreshes, sustaining usability and discoverability. This method showcases htmx’s capacity to create trendy internet apps whereas preserving them accessible and Web optimization-friendly.

Right here’s what we’ll find yourself with.

The code for this text may be discovered on the accompanying GitHub repo.

Stipulations

To comply with together with this tutorial, you’ll want Node.js put in in your PC. When you don’t have Node put in, please head to the official Node obtain web page and seize the right binaries to your system. Alternatively, you would possibly like to put in Node utilizing a model supervisor. This method means that you can set up a number of Node variations and change between them at will.

Aside from that, some familiarity with Node, Pug (which we’ll be utilizing because the template engine) and htmx could be useful, however not important. When you’d like a refresher on any of the above, try our tutorials: Construct a Easy Newbie App with Node, A Information to the Pug HTML Template Preprocessor and An Introduction to htmx.

Earlier than we start, run the next instructions:

node -v
npm -v

You need to see output like this:

v20.11.1
10.4.0

This confirms that Node and npm are put in in your machine and are accessible out of your command line setting.

Setting Up the Mission

Let’s begin by scaffolding a brand new Node undertaking:

mkdir contact-manager
cd contact-manager
npm init -y

This could create a bundle.json file within the undertaking root.

Subsequent, let’s set up the dependencies we’re going to want:

npm i categorical method-override pug

Of those packages, Categorical is the spine of our app. It’s a quick and minimalist internet framework which affords a simple option to deal with requests and responses, and to route URLs to particular handler capabilities. Pug will function our template engine, whereas we’ll use method-override to make use of HTTP verbs like PUT and DELETE in locations the place the consumer doesn’t help them.

Subsequent, create an app.js file within the root listing:

contact app.js

And add the next content material:

const categorical = require('categorical');
const path = require('path');
const routes = require('./routes/index');

const app = categorical();

app.set('views', path.be part of(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(categorical.static('public'));
app.use("https://www.sitepoint.com/", routes);

const server = app.hear(3000, () => {
  console.log(`Categorical is working on port ${server.tackle().port}`);
});

Right here, we’re establishing the construction of our Categorical app. This consists of configuring Pug as our view engine for rendering views, defining the listing for our static property, and hooking up our router.

The applying listens on port 3000, with a console log to verify that Categorical is working and able to deal with requests on the desired port. This setup varieties the bottom of our utility and is able to be prolonged with additional performance and routes.

Subsequent, let’s create our routes file:

mkdir routes
contact routes/index.js

Open that file and add the next:

const categorical = require('categorical');
const router = categorical.Router();


router.get('/contacts', async (req, res) => {
  res.ship('It really works!');
});

Right here, we’re establishing a fundamental route inside our newly created routes listing. This route listens for GET requests on the /contacts endpoint and responds with a easy affirmation message, indicating that every part is functioning correctly.

Subsequent, replace the “scripts” part of the bundle.json file with the next:

"scripts": {
  "dev": "node --watch app.js"
},

This makes use of the brand new watch mode in Node.js, which can restart our app every time any adjustments are detected.

Lastly, boot every part up with npm run dev and head to http://localhost:3000/contacts/ in your browser. You need to see a message saying “It really works!”.

The skeleton app running in a browser, displaying the message “It works!”

Thrilling instances!

Now let’s add some contacts to show. As we’re specializing in htmx, we’ll use a hard-coded array for simplicity. This may preserve issues streamlined, permitting us to give attention to htmx’s dynamic options with out the complexity of database integration.

For these curious about including a database afterward, SQLite and Sequelize are nice selections, providing a file-based system that doesn’t require a separate database server.

With that stated, please add the next to index.js earlier than the primary route:

const contacts = [
  { id: 1, name: 'John Doe', email: 'john.doe@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' },
  { id: 3, name: 'Emily Johnson', email: 'emily.johnson@example.com' },
  { id: 4, name: 'Aarav Patel', email: 'aarav.patel@example.com' },
  { id: 5, name: 'Liu Wei', email: 'liu.wei@example.com' },
  { id: 6, name: 'Fatima Zahra', email: 'fatima.zahra@example.com' },
  { id: 7, name: 'Carlos Hernández', email: 'carlos.hernandez@example.com' },
  { id: 8, name: 'Olivia Kim', email: 'olivia.kim@example.com' },
  { id: 9, name: 'Kwame Nkrumah', email: 'kwame.nkrumah@example.com' },
  { id: 10, name: 'Chen Yu', email: 'chen.yu@example.com' },
];

Now we have to create a template for our path to show. Create a views folder containing an index.pug file:

mkdir views
contact views/index.pug

And add the next:

doctype html
html
  head
    meta(charset='UTF-8')
    title Contact Supervisor

    hyperlink(rel='preconnect', href='https://fonts.googleapis.com')
    hyperlink(rel='preconnect', href='https://fonts.gstatic.com', crossorigin)
    hyperlink(href='https://fonts.googleapis.com/css2?household=Roboto:wght@300;400&show=swap', rel='stylesheet')

    hyperlink(rel='stylesheet', href='/types.css')
  physique
    header
      a(href='/contacts')
        h1 Contact Supervisor

    part#sidebar
      ul.contact-list
        every contact in contacts
          li #{contact.identify}
      div.actions
        a(href='/contacts/new') New Contact

    foremost#content material
      p Choose a contact

    script(src='https://unpkg.com/htmx.org@1.9.10')

On this template, we’re laying out the HTML construction for our utility. Within the head part, we’re together with the Roboto font from Google Fonts and a stylesheet for customized types.

The physique is split right into a header, a sidebar for itemizing contacts, and a foremost content material space the place all of our contact data will go. The content material space presently accommodates a placeholder. On the finish of the physique we’re additionally together with the most recent model of the htmx library from a CDN.

The template expects to obtain an array of contacts (in a contacts variable), which we iterate over within the sidebar and output every contact identify in an unordered checklist utilizing Pug’s interpolation syntax.

Subsequent, let’s create the customized stylesheet:

mkdir public
contact public/types.css

I don’t intend to checklist the types right here. Please copy them from the CSS file within the accompanying GitHub repo, or be at liberty so as to add a few of your individual. 🙂

Again in index.js, let’s replace our route to make use of the template:


router.get('/contacts', (req, res) => {
  res.render('index', { contacts });
});

Now if you refresh the web page you need to see one thing like this.

Contact manager displaying a list of contacts

Up to now, all we’ve executed is about up a fundamental Categorical app. Let’s change that and eventually add htmx to the combination. The subsequent step is to make it in order that when a person clicks on a contact within the sidebar, that contact’s data is displayed in the primary content material space — naturally and not using a full web page reload.

To begin with, let’s transfer the sidebar into its personal template:

contact views/sidebar.pug

Add the next to this new file:

ul.contact-list
  every contact in contacts
    li
      a(
        href=`/contacts/${contact.id}`,
        hx-get=`/contacts/${contact.id}`,
        hx-target='#content material',
        hx-push-url='true'
      )= contact.identify

div.actions
  a(href='/contacts/new') New Contact

Right here we now have made every contact a hyperlink pointing to /contacts/${contact.id} and added three htmx attributes:

  • hx-get. When the person clicks a hyperlink, htmx will intercept the press and make a GET request through Ajax to the /contacts/${contact.id} endpoint.
  • hx-target. When the request completes, the response can be inserted into the div with an ID of content material. We haven’t specified any form of swap technique right here, so the contents of the div can be changed with no matter is returned from the Ajax request. That is the default habits.
  • hx-push-url. This may make sure that the worth laid out in htx-get is pushed onto the browser’s historical past stack, altering the URL.

Replace index.pug to make use of our template:

part#sidebar
  embody sidebar.pug

Keep in mind: Pug is white area delicate, so remember to use the right indentation.

Now let’s create a brand new endpoint in index.js to return the HTML response that htmx is anticipating:


router.get('/contacts/:id', (req, res) => {
  const { id } = req.params;
  const contact = contacts.discover((c) => c.id === Quantity(id));

  res.ship(`
    <h2>${contact.identify}</h2>
    <p><robust>Title:</robust> ${contact.identify}</p>
    <p><robust>Electronic mail:</robust> ${contact.e-mail}</p>
  `);
});

When you save this and refresh your browser, you need to now have the ability to view the main points of every contact.

The final app

HTML over the wire

Let’s take a second to know what’s happening right here. As talked about at the start of the article, htmx delivers HTML over the wire, versus the JSON payload related to conventional frontend frameworks.

We are able to see this if we open our browser’s developer instruments, change to the Community tab and click on on one of many contacts. Upon receiving a request from the frontend, our Categorical app generates the HTML wanted to show that contact and sends it to the browser, the place htmx swaps it into the right place within the UI.

Developer tools showing the request for /contacts/1 in the Network tab

So issues are going fairly nicely, huh? Due to htmx, we simply made our web page dynamic by specifying a few attributes on an anchor tag. Sadly, there’s an issue…

When you show a contact, then refresh the web page, our pretty UI is gone and all you see is the naked contact particulars. The identical will occur if you happen to load the URL immediately in your browser.

The rationale for that is apparent if you consider it. If you entry a URL similar to http://localhost:3000/contacts/1, the Categorical route for '/contacts/:id' kicks in and returns the HTML for the contact, as we’ve advised it to do. It is aware of nothing about the remainder of our UI.

To fight this, we have to make a few adjustments. On the server, we have to test for an HX-Request header, which signifies that the request got here from htmx. If this header exists, then we are able to ship our partial. In any other case, we have to ship the complete web page.

Change the route handler like so:


router.get('/contacts/:id', (req, res) => {
  const { id } = req.params;
  const contact = contacts.discover((c) => c.id === Quantity(id));

  if (req.headers['hx-request']) {
    res.ship(`
      <h2>${contact.identify}</h2>
      <p><robust>Title:</robust> ${contact.identify}</p>
      <p><robust>Electronic mail:</robust> ${contact.e-mail}</p>
    `);
  } else {
    res.render('index', { contacts });
  }
});

Now, if you reload the web page, the UI doesn’t disappear. It does, nonetheless, revert from whichever contact you had been viewing to the message “Choose a contact”, which isn’t excellent.

To repair this, we are able to introduce a case assertion to our index.pug template:

foremost#content material
  case motion
    when 'present'
      h2 #{contact.identify}
      p #[strong Name:] #{contact.identify}
      p #[strong Email:] #{contact.e-mail}
    when 'new'
      
    when 'edit'
      
    default
      p Choose a contact

And eventually replace the route handler:

if (req.headers['hx-request']) {
  
} else {
  res.render('index', { motion: 'present', contacts, contact });
}

Notice that we’re now passing in a contact variable, which can be used within the occasion of a full web page reload.

And with this, our app ought to face up to being refreshed or having a contact loaded immediately.

A fast refactor

Though this works, you would possibly discover that we now have some duplicate content material in each our route handler and our foremost pug template. This isn’t excellent, and issues will begin to get unwieldy as quickly as a contact has something greater than a handful of attributes, or we have to use some logic to determine which attributes to show.

To counteract this, let’s transfer contact into its personal template:

contact views/contact.pug

Within the newly created template, add this:

h2 #{contact.identify}

p #[strong Name:] #{contact.identify}
p #[strong Email:] #{contact.e-mail}

In the primary template (index.pug):

foremost#content material
  case motion
    when 'present'
      embody contact.pug

And our route handler:

if (req.headers['hx-request']) {
  res.render('contact', { contact });
} else {
  res.render('index', { motion: 'present', contacts, contact });
}

Issues ought to nonetheless work as earlier than, however now we’ve eliminated the duplicated code.

The subsequent process to show our consideration to is creating a brand new contact. This a part of the tutorial will information you thru establishing the shape and backend logic, utilizing htmx to deal with submissions dynamically.

Let’s begin by updating our sidebar template. Change:

div.actions
  a(href='/contacts/new') New Contact

… to:

div.actions
  a(
    href='/contacts/new',
    hx-get='/contacts/new',
    hx-target='#content material',
    hx-push-url='true'
  ) New Contact

This makes use of the identical htmx attributes as our hyperlinks to show a contact: hx-get will make a GET request through Ajax to the /contacts/new endpoint, hx-target specifies the place to insert the response, and hx-push-url will make sure that the URL is modified.

Now let’s create a brand new template for the shape:

contact views/type.pug

And add the next code:

h2 New Contact

type(
  motion='/contacts',
  methodology='POST',
  hx-post='/contacts',
  hx-target='#sidebar',
  hx-on::after-request='if(occasion.element.profitable) this.reset()'
)
  label(for='identify') Title:
  enter#identify(sort='textual content', identify='identify', required)

  label(for='e-mail') Electronic mail:
  enter#e-mail(sort='e-mail', identify='e-mail', required)

  div.actions
    button(sort='submit') Submit

Right here, we’re utilizing the hx-post attribute to inform htmx to intercept the shape submission and make a POST request with the shape information to the /contacts endpoint. The outcome (an up to date checklist of contacts) can be inserted into the sidebar. We don’t need to change the URL on this case, because the person would possibly need to enter a number of new contacts. We do, nonetheless, need to empty the shape after a profitable submission, which is what the hx-on::after-request does. The hx-on* attributes permit you to embed scripts inline to answer occasions immediately on a component. You may learn extra about it right here.

Subsequent, let’s add a route for the shape in index.js:


...


router.get('/contacts/new', (req, res) => {
  if (req.headers['hx-request']) {
    res.render('type');
  } else {
    res.render('index', { motion: 'new', contacts, contact: {} });
  }
});


...

Route order is necessary right here. When you’ve got the '/contacts/:id' route first, then Categorical will try to discover a contact with the ID of new.

Lastly, replace our index.pug template to make use of the shape:

when 'new'
  embody type.pug

Refresh the web page, and at this level you need to have the ability to render the brand new contact type by clicking on the New Contact hyperlink within the sidebar.

The New Contact form

Now we have to create a path to deal with type submission.

First replace app.js to present us entry to the shape’s information inside our route handler.

const categorical = require('categorical');
const path = require('path');
const routes = require('./routes/index');

const app = categorical();

app.set('views', path.be part of(__dirname, 'views'));
app.set('view engine', 'pug');

+ app.use(categorical.urlencoded({ prolonged: true }));
app.use(categorical.static('public'));
app.use("https://www.sitepoint.com/", routes);

const server = app.hear(3000, () => {
  console.log(`Categorical is working on port ${server.tackle().port}`);
});

Beforehand, we might have used the body-parser bundle, however I just lately realized that is not mandatory.

Then add the next to index.js:


router.publish('/contacts', (req, res) => {
  const newContact = {
    id: contacts.size + 1,
    identify: req.physique.identify,
    e-mail: req.physique.e-mail,
  };

  contacts.push(newContact);

  if (req.headers['hx-request']) {
    res.render('sidebar', { contacts });
  } else {
    res.render('index', { motion: 'new', contacts, contact: {} });
  }
});

Right here, we’re creating a brand new contact with the info we obtained from the consumer and including it to the contacts array. We’re then re-rendering the sidebar, passing it the up to date checklist of contacts.

Notice that, if you happen to’re making any form of utility that has customers, it’s as much as you to validate the info you’re receiving from the consumer. In our instance, I’ve added some fundamental client-side validation, however this will simply be bypassed.

There’s an instance of the best way to validate enter on the server utilizing the express-validator bundle bundle within the Node tutorial I linked to above.

Now, if you happen to refresh your browser and take a look at including a contact, it ought to work as anticipated: the brand new contact needs to be added to the sidebar and the shape needs to be reset.

Including flash messages

That is nicely and good, however now we want a option to inform the person {that a} contact has been added. In a typical utility, we might use a flash message — a short lived notification that alerts the person concerning the consequence of an motion.

The issue we encounter with htmx is that we’re updating the sidebar after efficiently creating a brand new contact, however this isn’t the place we would like our flash message to be displayed. A greater location could be above the brand new contact type.

To get round this, we are able to use the hx-swap-oob attribute. This lets you specify that some content material in a response needs to be swapped into the DOM someplace aside from the goal, that’s “Out of Band”.

Replace the route handler as follows:

if (req.headers['hx-request']) {
  res.render('sidebar', { contacts }, (err, sidebarHtml) => {
    const html = `
      <foremost id="content material" hx-swap-oob="afterbegin">
        <p class="flash">Contact was efficiently added!</p>
      </foremost>
      ${sidebarHtml}
    `;
    res.ship(html);
  });
} else {
  res.render('index', { motion: 'new', contacts, contact: {} });
}

Right here, we’re rendering the sidebar as earlier than, however passing the render methodology an nameless perform because the third parameter. This perform receives the HTML generated by calling res.render('sidebar', { contacts }), which we are able to then use to assemble our ultimate response.

By specifying a swap technique of "afterbegin", the flash message is inserted on the prime of the container.

Now, after we add a contact, we should always get a pleasant message informing us what occurred.

Contact was successfully added

For updating a contact, we’re going to reuse the shape we created within the earlier part.

Let’s begin by updating our contact.pug template so as to add the next:

div.actions
  a(
    href=`/contacts/${contact.id}/edit`,
    hx-get=`/contacts/${contact.id}/edit`,
    hx-target='#content material',
    hx-push-url='true'
  ) Edit Contact

This may add an Edit Contact button beneath a contacts particulars. As we’ve seen earlier than, when the hyperlink is clicked, hx-get will make a GET request through Ajax to the /${contact.id}/edit endpoint, hx-target will specify the place to insert the response, and hx-push-url will make sure that the URL is modified.

Now let’s alter our index.pug template to make use of the shape:

when 'edit'
  embody type.pug

Additionally add a route handler to show the shape:


router.get('/contacts/:id/edit', (req, res) => {
  const { id } = req.params;
  const contact = contacts.discover((c) => c.id === Quantity(id));

  if (req.headers['hx-request']) {
    res.render('type', { contact });
  } else {
    res.render('index', { motion: 'edit', contacts, contact });
  }
});

Notice that we’re retrieving the contact utilizing the ID from the request, then passing that contact to the shape.

We’ll additionally have to replace our new contact handler to do the identical, however right here passing an empty object:

// GET /contacts/new
router.get('/contacts/new', (req, res) => {
  if (req.headers['hx-request']) {
-    res.render('type');
+    res.render('type', { contact: {} });
  } else {
    res.render('index', { motion: 'new', contacts, contact: {} });
  }
});

Then we have to replace the shape itself:

- isEditing = () => !(Object.keys(contact).size === 0);

h2=isEditing() ? "Edit Contact" : "New Contact"

type(
  motion=isEditing() ? `/replace/${contact.id}?_method=PUT` : '/contacts',
  methodology='POST',

  hx-post=isEditing() ? false : '/contacts',
  hx-put=isEditing() ? `/replace/${contact.id}` : false,
  hx-target='#sidebar',
  hx-push-url=isEditing() ? `/contacts/${contact.id}` : false
  hx-on::after-request='if(occasion.element.profitable) this.reset()',
)
  label(for='identify') Title:
  enter#identify(sort='textual content', identify='identify', required, worth=contact.identify)

  label(for='e-mail') Electronic mail:
  enter#e-mail(sort='e-mail', identify='e-mail', required, worth=contact.e-mail)

  div.actions
    button(sort='submit') Submit

As we’re passing in both a contact or an empty object to this way, we now have a simple option to decide if we’re in “edit” or “create” mode. We are able to do that by checking Object.keys(contact).size. We are able to additionally extract this test into somewhat helper perform on the prime of the file utilizing Pug’s unbuffered code syntax.

As soon as we all know which mode we discover ourselves in, we are able to conditionally change the web page title, then determine which attributes we add to the shape tag. For the edit type, we have to add a hx-put attribute and set it to /replace/${contact.id}. We additionally have to replace the URL as soon as the contact’s particulars have been saved.

To do all of this, we are able to make the most of the truth that, if a conditional returns false, Pug will omit the attribute from the tag.

Which means that this:

type(
  motion=isEditing() ? `/replace/${contact.id}?_method=PUT` : '/contacts',
  methodology='POST',

  hx-post=isEditing() ? false : '/contacts',
  hx-put=isEditing() ? `/replace/${contact.id}` : false,
  hx-target='#sidebar',
  hx-on::after-request='if(occasion.element.profitable) this.reset()',
  hx-push-url=isEditing() ? `/contacts/${contact.id}` : false
)

… will compile to the next when isEditing() returns false:

<type 
  motion="/contacts" 
  methodology="POST" 
  hx-post="/contacts" 
  hx-target="#sidebar" 
  hx-on::after-request="if(occasion.element.profitable) this.reset()"
>
  ...
</type>

However when isEditing() returns true, it is going to compile to:

<type 
  motion="/replace/1?_method=PUT" 
  methodology="POST" 
  hx-put="/replace/1" 
  hx-target="#sidebar" 
  hx-on::after-request="if(occasion.element.profitable) this.reset()" 
  hx-push-url="/contacts/1"
>
  ...
</type>

In its replace state, discover that the shape motion is "/replace/1?_method=PUT". This question string parameter has been added as a result of we’re utilizing the method-override bundle, and it’ll make our router reply to a PUT request.

Out of the field, htmx can ship PUT and DELETE requests, however the browser can’t. Because of this, if we need to cope with a state of affairs the place JavaScript is disabled, we would want to duplicate our route handler, having it reply to each PUT (htmx) and POST (the browser). Utilizing this middleware will preserve our code DRY.

Let’s go forward and add it to app.js:

const categorical = require('categorical');
const path = require('path');
+ const methodOverride = require('method-override');
const routes = require('./routes/index');

const app = categorical();

app.set('views', path.be part of(__dirname, 'views'));
app.set('view engine', 'pug');

+ app.use(methodOverride('_method'));
app.use(categorical.urlencoded({ prolonged: true }));
app.use(categorical.static('public'));
app.use("https://www.sitepoint.com/", routes);

const server = app.hear(3000, () => {
  console.log(`Categorical is working on port ${server.tackle().port}`);
});

Lastly, let’s replace index.js with a brand new route handler:


router.put('/replace/:id', (req, res) => {
  const { id } = req.params;

  const newContact = {
    id: Quantity(id),
    identify: req.physique.identify,
    e-mail: req.physique.e-mail,
  };

  const index = contacts.findIndex((c) => c.id === Quantity(id));

  if (index !== -1) contacts[index] = newContact;

  if (req.headers['hx-request']) {
    res.render('sidebar', { contacts }, (err, sidebarHtml) => {
      res.render('contact', { contact: contacts[index] }, (err, contactHTML) => {
        const html = `
          ${sidebarHtml}
          <foremost id="content material" hx-swap-oob="true">
            <p class="flash">Contact was efficiently up to date!</p>
            ${contactHTML}
          </foremost>
        `;

        res.ship(html);
      });
    });
  } else {
    res.redirect(`/contacts/${index + 1}`);
  }
});

Hopefully there’s nothing too mysterious right here by now. At the start of the handler we seize the contact ID from the request params. We then discover the contact we want to replace and swap it out with a brand new contact created from the shape information we obtained.

When coping with an htmx request, we first render the sidebar template with our up to date contacts checklist. We then render the contact template with the up to date contact and use the results of each of those calls to assemble our response. As earlier than, we use an “Out of Band” replace to create a flash message informing the person that the contact was up to date.

At this level, you need to have the ability to replace contacts.

Contact was successfully updated

The ultimate piece of the puzzle is the flexibility to delete contacts. Let’s add a button to do that to our contact template:

div.actions
  type(methodology='POST', motion=`/delete/${contact.id}?_method=DELETE`)
    button(
      sort='submit',
      hx-delete=`/delete/${contact.id}`,
      hx-target='#sidebar',
      hx-push-url='/contacts'
      class='hyperlink'
    ) Delete Contact

  a( 
    
  )

Notice that it’s good observe to make use of a type and a button to difficulty the DELETE request. Varieties are designed for actions that trigger adjustments, like deletions, and this ensures semantic correctness. Moreover, utilizing a hyperlink for a delete motion might be dangerous as a result of search engines like google can inadvertently comply with hyperlinks, doubtlessly resulting in undesirable deletions.

That being stated, I’ve added some CSS to type the button like a hyperlink, as buttons are ugly. When you copied the types from the repo earlier than, you have already got this in your code.

And eventually, our route handler in index.js:


router.delete('/delete/:id', (req, res) => {
  const { id } = req.params;
  const index = contacts.findIndex((c) => c.id === Quantity(id));

  if (index !== -1) contacts.splice(index, 1);
  if (req.headers['hx-request']) {
    res.render('sidebar', { contacts }, (err, sidebarHtml) => {
      const html = `
        <foremost id="content material" hx-swap-oob="true">
          <p class="flash">Contact was efficiently deleted!</p>
        </foremost>
        ${sidebarHtml}
      `;
      res.ship(html);
    });
  } else {
    res.redirect('/contacts');
  }
});

As soon as the contact has been eliminated, we’re updating the sidebar and displaying the person a flash message.

Contact was successfully deleted

Taking It Additional

And that’s a wrap.

On this article, we’ve crafted a full-stack CRUD utility utilizing Node and Categorical for the backend and htmx for the frontend. Alongside the way in which, I’ve demonstrated how htmx can simplify including dynamic habits to your internet apps, decreasing the necessity for complicated JavaScript and full-page reloads, and thus making the person expertise smoother and extra interactive.

And as an added bonus, the app additionally capabilities nicely with out JavaScript.

But whereas our app is absolutely practical, it’s admittedly somewhat bare-bones. When you want to proceed exploring htmx, you would possibly like to take a look at implementing view transitions between app states, or including some additional validation to the shape — for instance, to confirm that the e-mail tackle comes from a particular area.

I’ve examples of each of this stuff (and extra moreover) in my Introduction to htmx.

Aside from that, you probably have any questions or feedback, please attain out on X.

Completely happy coding!





Supply hyperlink

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article