0
0
Expressframework~15 mins

EJS template setup in Express - Deep Dive

Choose your learning style9 modes available
Overview - EJS template setup
What is it?
EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML pages with dynamic content using JavaScript. It works by mixing plain HTML with special tags that insert JavaScript code or variables. Setting up EJS in an Express app means configuring Express to use EJS files to render views when users visit your website.
Why it matters
Without EJS or a similar templating system, your web pages would be static and unable to show personalized or changing content like user names, lists, or dates. EJS solves this by letting you write HTML that can change based on data from your server, making websites interactive and user-friendly. Without it, developers would have to build HTML strings manually, which is error-prone and hard to maintain.
Where it fits
Before learning EJS setup, you should know basic JavaScript and how Express handles routes and requests. After mastering EJS setup, you can learn more advanced templating features, partial views, and how to combine EJS with CSS and client-side JavaScript for full web apps.
Mental Model
Core Idea
EJS templates are like blueprints that combine fixed HTML with placeholders that get filled with live data when the page is created.
Think of it like...
Imagine a cookie cutter (the EJS template) that shapes dough (HTML) but also stamps a name or date on each cookie (dynamic data) before baking (sending to the browser).
Express App
  │
  ├─ Routes handle requests
  │    │
  │    └─ Calls res.render('template', data)
  │                 │
  │                 └─ EJS template engine fills placeholders
  │                       │
  │                       └─ Sends final HTML to browser
Build-Up - 6 Steps
1
FoundationInstall EJS and Express basics
🤔
Concept: Learn how to add EJS to an Express project and understand the basic Express app structure.
Start a new Node.js project and install Express and EJS using npm: npm init -y npm install express ejs Create a simple Express app in app.js that listens on a port but does not yet use EJS.
Result
You have a working Express server ready to add EJS templating.
Knowing how to install and set up the basic Express app is essential before adding templating features.
2
FoundationConfigure Express to use EJS
🤔
Concept: Set Express to use EJS as its view engine and understand where to put EJS files.
In your app.js, add: app.set('view engine', 'ejs'); Create a folder named 'views' in your project root. Place EJS files there, for example, views/index.ejs. This tells Express to look in 'views' for .ejs files to render.
Result
Express knows to use EJS files in the views folder to render HTML pages.
Configuring the view engine connects Express with EJS, enabling dynamic page rendering.
3
IntermediateCreate and render a basic EJS template
🤔Before reading on: do you think EJS templates can include plain HTML mixed with JavaScript code? Commit to your answer.
Concept: Learn how to write a simple EJS file with HTML and insert dynamic data passed from Express.
Create views/index.ejs with:

Welcome, <%= name %>!

In app.js, add a route: app.get('/', (req, res) => { res.render('index', { name: 'Friend' }); });
Result
Visiting '/' shows a page with 'Welcome, Friend!' where 'Friend' is dynamic data.
Understanding how EJS tags like <%= %> insert data is key to making pages dynamic.
4
IntermediateUse EJS control flow tags
🤔Before reading on: do you think EJS supports JavaScript if statements and loops inside templates? Commit to your answer.
Concept: Learn how to use EJS tags to add logic like conditions and loops inside templates.
In your EJS file, you can write:
    <% for(let i=0; i < items.length; i++) { %>
  • <%= items[i] %>
  • <% } %>
Pass items array from Express: app.get('/list', (req, res) => { res.render('index', { items: ['apple', 'banana', 'cherry'] }); });
Result
The page shows a list of fruits dynamically generated from the array.
Using control flow in templates lets you build complex, data-driven HTML structures.
5
AdvancedOrganize templates with partials
🤔Before reading on: do you think EJS supports including one template inside another? Commit to your answer.
Concept: Learn how to split templates into reusable parts called partials to avoid repetition.
Create a partial file views/partials/header.ejs:

Site Title

In your main template, include it with: <%- include('partials/header') %> This inserts the header content wherever you place the include tag.
Result
Your pages share the same header without copying code, making maintenance easier.
Partials promote DRY (Don't Repeat Yourself) principles and cleaner template organization.
6
ExpertUnderstand EJS rendering internals
🤔Before reading on: do you think EJS compiles templates to JavaScript functions before rendering? Commit to your answer.
Concept: Explore how EJS converts templates into JavaScript functions that generate HTML strings at runtime.
EJS parses the template file and creates a JavaScript function where HTML is returned as strings and dynamic parts are inserted via JavaScript code. When res.render is called, this function runs with your data to produce the final HTML. This compilation step improves performance by reusing the function for multiple requests.
Result
You understand why EJS templates are fast and how errors in templates relate to JavaScript syntax.
Knowing the compilation process helps debug template errors and optimize rendering.
Under the Hood
EJS works by reading the template file and transforming it into a JavaScript function. This function contains code that outputs HTML strings and inserts dynamic data using JavaScript expressions. When Express calls res.render, it runs this function with the provided data, producing the final HTML string sent to the browser. The template engine caches compiled functions for efficiency.
Why designed this way?
EJS was designed to be simple and close to plain HTML, making it easy for developers to learn and use. Compiling templates to JavaScript functions allows fast rendering and leverages JavaScript's power for logic inside templates. Alternatives like string concatenation were slower and harder to maintain. The design balances simplicity, speed, and flexibility.
┌───────────────┐
│ EJS Template  │
│  (index.ejs)  │
└──────┬────────┘
       │ Parse & compile
       ▼
┌─────────────────────┐
│ JavaScript Function  │
│ (returns HTML string)│
└──────┬──────────────┘
       │ Execute with data
       ▼
┌─────────────────────┐
│ Final HTML Output    │
│ sent to browser      │
└─────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think EJS templates run on the browser by default? Commit to yes or no.
Common Belief:EJS templates are client-side code that runs in the browser to generate HTML.
Tap to reveal reality
Reality:EJS templates run on the server inside Node.js and generate HTML before sending it to the browser.
Why it matters:Thinking EJS runs in the browser leads to confusion about where data is processed and can cause security risks if sensitive data is exposed.
Quick: Do you think EJS automatically escapes all HTML to prevent security issues? Commit to yes or no.
Common Belief:EJS automatically escapes all inserted data to prevent cross-site scripting (XSS).
Tap to reveal reality
Reality:EJS escapes data only when using <%= %> tags; using <%- %> outputs raw HTML without escaping.
Why it matters:Misunderstanding this can cause security vulnerabilities if raw HTML is output without proper sanitization.
Quick: Do you think you can use any JavaScript code inside EJS templates? Commit to yes or no.
Common Belief:EJS templates support all JavaScript features and complex logic inside templates.
Tap to reveal reality
Reality:While EJS supports JavaScript syntax, complex logic should be avoided in templates to keep them clean; heavy logic belongs in server code.
Why it matters:Putting too much logic in templates makes code hard to read, debug, and maintain.
Quick: Do you think EJS templates must be recompiled on every request? Commit to yes or no.
Common Belief:EJS recompiles templates from scratch on every page request.
Tap to reveal reality
Reality:EJS caches compiled templates in memory to improve performance and avoid recompiling each time.
Why it matters:Not knowing about caching can lead to inefficient code or confusion when changes don't appear immediately during development.
Expert Zone
1
EJS allows mixing raw HTML and JavaScript, but subtle differences between <%= %> (escaped output) and <%- %> (unescaped output) can cause security issues if misunderstood.
2
Template caching improves performance but requires manual cache clearing or server restart during development to see changes.
3
EJS does not natively support asynchronous code inside templates, so all data must be prepared before rendering.
When NOT to use
EJS is not ideal for highly interactive client-side apps or when you need reactive UI updates; frameworks like React or Vue are better. Also, for very large projects, more structured templating engines or component-based systems may be preferable.
Production Patterns
In production, EJS templates are often combined with partials for headers and footers, layout templates for consistent page structure, and middleware to inject common data like user info. Templates are precompiled and cached for speed, and security practices ensure escaping user input.
Connections
Server-Side Rendering (SSR)
EJS is a form of SSR templating that generates HTML on the server before sending to the client.
Understanding EJS helps grasp how SSR works to improve SEO and initial load speed compared to client-side rendering.
MVC Architecture
EJS templates serve as the 'View' layer in the Model-View-Controller pattern used in web apps.
Knowing EJS's role clarifies how data flows from models through controllers to views for display.
Print Media Templates
Like EJS templates, print media templates combine fixed layout with placeholders for dynamic content like names or dates.
Recognizing this similarity shows how templating is a universal pattern for mixing static and dynamic content.
Common Pitfalls
#1Not setting the view engine in Express causes errors when rendering templates.
Wrong approach:app.get('/', (req, res) => { res.render('index', { name: 'Friend' }); }); // but no app.set('view engine', 'ejs')
Correct approach:app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', { name: 'Friend' }); });
Root cause:Express doesn't know which template engine to use without the view engine setting.
#2Using <%- %> tags without sanitizing user input leads to security risks.
Wrong approach:<%- userInput %> // outputs raw HTML from user input
Correct approach:<%= userInput %> // escapes HTML to prevent XSS
Root cause:Confusing escaped and unescaped output tags causes injection vulnerabilities.
#3Placing heavy business logic inside EJS templates makes code messy and hard to maintain.
Wrong approach:<% if(user.isAdmin && user.hasPermission('edit')) { %> ... complex logic ... <% } %>
Correct approach:// Prepare flags in server code const canEdit = user.isAdmin && user.hasPermission('edit'); res.render('index', { canEdit }); // In template <% if(canEdit) { %> ... <% } %>
Root cause:Mixing logic and presentation violates separation of concerns.
Key Takeaways
EJS templates combine HTML with JavaScript placeholders to create dynamic web pages on the server.
Configuring Express to use EJS involves setting the view engine and placing templates in the views folder.
EJS supports JavaScript control flow and partials to build flexible and reusable templates.
Understanding how EJS compiles templates to JavaScript functions helps debug and optimize rendering.
Security depends on using the correct EJS tags to escape user input and keeping logic out of templates.