Why does my liquid code return an empty string for canonical URL?

Topic summary

A developer encountered an issue where Liquid code for generating canonical URLs was returning an empty string. The goal was to strip query parameters (like ?page=srnqqdjnmld) from collection URLs to display clean canonical URLs.

Root Cause:
The problem was caused by extra curly braces {{ }} in the variable assignment: {% assign canonicalUrl = {{ canonical_url }} %}. This syntax error prevented proper variable assignment.

Solution:
Removing the extra braces fixes the issue: {% assign canonicalUrl = canonical_url %}

Additional Context:

  • One responder noted that Shopify’s canonical_url variable already returns the page’s default URL with parameters removed, making additional manipulation unnecessary.
  • A follow-up question raised whether the conditional check should use == instead of != for the page parameter comparison, though this wasn’t definitively resolved.

Status: Issue resolved through syntax correction.

Summarized with AI on November 15. AI used: claude-sonnet-4-5-20250929.

Hi,

We are trying to return the true canonical value instead of an url with a search parameter.

So instead of having something like this:

[domain]/collections/jackets-coats?page=srnqqdjnmld

We would like to show something like this:

[domain]/collections/jackets-coats

Does anyone knows why the following code returns an empty string?

{% assign canonicalUrl = {{ canonical_url }} %} 
 
 {% assign secondUrl = canonicalUrl | split: '?' | last %}
 {% if secondUrl != 'page=2' %}
 {% assign canonicalUrl = canonicalUrl | split: '?' | first %}
 {% endif %}

Code above works in a liquid sandbox.

Thanks.

Cheers,

Gonkas

Hi @Gonkas ,

Please change code:

{% assign canonicalUrl = canonical_url %} 
 
{% assign secondUrl = canonicalUrl | split: '?' | last %}
{% if secondUrl != 'page=2' %}
{% assign canonicalUrl = canonicalUrl | split: '?' | first %}
{% endif %}

Hope it helps!

1 Like

The issue is extra {{ }} {% assign canonicalUrl = {{ canonical_url }} %}

This is the correct code: {% assign canonicalUrl = canonical_url %}

But the canonical URL is the page’s “default” URL with any URL parameters removed so nothing more needs to be done.

For example, for a product in a collection with a variant selected:

https://example.com/collections/classics/products/shoes?variant=17287731270

The canonical URL is the product page: https://example.com/products/shoes

Have a great day!!!


  • Was I helpful? Like to let me know :slightly_smiling_face:

  • Did I answer your question? Mark my reply as Accepted Solution

1 Like

Thanks both, it was extra {{ }}.

Shopify should work that out but it doesn’t so needs this “hack”.

Have a great day!

1 Like

Shouldn’t it be:

{% if secondUrl == "page=2" %}

Your code doesn’t work for me, but after making that change it does.