javascripthtmlnode.jssails.jsmeta-tags

How to set meta description in Sails JS 1.0


How to set a meta description tag in a Sails JS version 1.0 app for SEO optimization?

I have a web app but the indexing in Google is not respecting what I want. The description under links are not useful for the users to understand what that page allows us to do.

I read THIS implementation for meta description tags but it's for sails version < 1.0, and I don't know how to replicate it in version 1.0.

My routes.js file is like this:

module.exports.routes = {

  // WEB PAGES
  'GET /':                                        { action: 'auth/view-homepage-or-redirect' },
  'GET /login':                                   { action: 'auth/view-login' },
  'GET /register':                                { action: 'auth/view-register' },
  ...
  ...
  ...

As you can see I'm using sails actions and the standard ejs HTML template. So I've a layout.ejs file that incorporate all the other pages (.ejs) as body in.

This is my login.ejs file:

<div id="login" v-cloak>
  <div class="container">
    <h1 class="text-center"><%= __('Sign in to your account') %></h1>
    <div class="login-form-container">
      <hr/>
      <form id="login-form">
        <-- LOGIN FORM implementation !-->
      </form>
      <div class="text-center"><small><a href="/register"><%= __('Don\'t have an account?') %></a></small></div>
    </div>
  </div>
</div>

Solution

  • The question you've linked isn't too far gone that it won't work with Sails v1 without a few tweaks.

    The <meta> tag is going to need to be between the HTML <head></head> tags, so assuming you have a layout.ejs or similar we're going to need to add something in there.

    <title>...</title>
    <% if (typeof metaDescription !== 'undefined') { %>
      <meta name="description" content="<%= metaDescription %>">
    <% } %>
    

    This should ensure that if the metaDescription is set then it'll get added into the HTML, but should avoid any undefined errors if you don't specify the meta description for a route.

    There are a few ways you could actually set the description for each page.

    In an actions2 controller, you could do something like the following. This could be useful if you need to generate (parts of) the description dynamically.

    return res.success({
      metaDescription: '...',
      otherViewVar: '...',
      // ...
    })
    

    You could also set the value in your config/routes.js file

    module.exports.routes = {
      'GET /': { 
        action: 'auth/view-homepage-or-redirect',
        locals: {
          metaDescription: '...'
        }
      },
      // ...
    }