Using external libs in EJS

<script src=""></script>

var d =
var time = dayjs(d).format("MMM DD, YYYY - HH:mm:ss (hh:mm:ss A)")


<p><b>Date posted:<b/><%-time%></p>

This code doesn’t render right - it serves an error: dayjs is not defined
I tried putting the dayjs code in script tags - it runs alright, but now “time” is not defined.

How can I use an external lib with EJS?

The script tags are a script to run on the client.

The <% … %> tags are run on the server, or the client if you want.

So you can do either:

a. Calculate the time on the client


b. Use require to bring in a module on the server


c. Configure EJS to run in the browser

How are you using EJS?

I need to run DayJS on the client because the lib automatically detects the client time zone - this can’t happen on the server.

Maybe I could do this:

var dayjs = require("dayjs")
res.render("uniquepost", {
dayjs: dayjs,
title: post.title,
body: post.body

I guess because dayjs is only 2kb it wouldn’t take too long to load. What do you think?

How about the server passes the date value to javascript in the client … I’m not sure what format <> will be, should work if it is like 1600666077974.

<script src=""></script>

<p><b>Date posted:</b><span id="posttime"></span></p>

    var time = dayjs(<>).format("MMM DD, YYYY - HH:mm:ss (hh:mm:ss A)")
    document.getElementById("posttime").textContent = time;
1 Like

That’s a smart idea - I didn’t know you could use EJS tags in script tags! I’ll try this out right now.

Ok, it actually doesn’t work…

  1. <%- post %> is succesfully passed - it forms an [object Object]
  2. However, for some reason it’s undefined - dayjs appears client side with no arguments.
  3. So then I just tested
    var obj = <%- post %>

Screen Shot 2020-09-21 at 11.16.30 AM

This is sadly not working, so I’m probably going to try to use fetch and start a GET endpoint on my web app to get the time.

If is a date object, you could pass the milliseconds string to the script via


Otherwise your idea to fetch it later should work.

1 Like is a number like 1566039843. I’ll just have to do complex acrobatics like parse the sent URL, and fetch with the id, and this and that rip.

Another alternative is render to a hidden HTML element, then pull its value with javascript.

Are you sure? What does this show

1 Like

I just checked out the EJS docs, and there’s a possibility we’ve been using the wrong tags. The docs show obj.key in <%= tags. I’m testing that right now.

Screen Shot 2020-09-21 at 5.30.53 PM

Orange means number, green means string, etc.

So <%= post %> returns nothing, and <%= %> returns object Object.

What I can do is set a div to be, and then use a window.onload function to get the value of the div.