DEV Community

Cover image for How To Fetch (Get) HTML From Server 🛤️

How To Fetch (Get) HTML From Server 🛤️

Anthony Max on March 14, 2025

With the development of server-oriented development, when it is necessary to take templates from the server, there is a need to send HTML code to t...
Collapse
 
dperrymorrow profile image
David Morrow
const res = await fetch('/api/getForm');
const html = await res.text();
Enter fullscreen mode Exit fullscreen mode

much less verbose if you use async await instead of a promise chain. For error handling, just wrap the whole thing in a try / catch.

Collapse
 
anthonymax profile image
Anthony Max

It's possible that way too, yes

Collapse
 
key_master1 profile image
Key Master1

You forgot to put a semicolon in the example.

console.log(html)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anthonymax profile image
Anthony Max

Corrected

Collapse
 
anthonymax profile image
Anthony Max

Thanks!

Collapse
 
learncomputer profile image
Learn Computer Academy

Awesome breakdown of fetching HTML from the server! I like how you covered both the hmpl-js library and vanilla JS approaches—great to see the pros and cons laid out clearly. The backend setup with Express.js ties it all together nicely too. Definitely helpful for anyone diving into server-client templating. Thanks for sharing—looking forward to more!

Collapse
 
anthonymax profile image
Anthony Max

Thanks!

Collapse
 
webjose profile image
José Pablo Ramírez Vargas
Collapse
 
tylish_anup_71a651f92d0fd profile image
Tylish Anup

I like this Article

Collapse
 
alexpa292 profile image
Alex Patla

Great article!

Collapse
 
anthonymax profile image
Anthony Max

Thanks!

Collapse
 
anthonymax profile image
Anthony Max • Edited

You can also add such a condition to determine with high accuracy that it is text/html:

if (response.headers.get("Content-Type") !== "text/html") {
  // some code
}
Enter fullscreen mode Exit fullscreen mode

In the example, I didn’t want to overload it with unnecessary code.