In my website I want to build a functionality that if a non logged in user enters the website it will redirected to the login or register page and if a logged in user enters the website they can redirect to website landing page.
Topic summary
Problem: A user wanted to redirect non-logged-in visitors to a login/signup page while allowing logged-in customers to access the main site.
Initial Solution: The original poster resolved continuous reload issues by implementing code in theme.liquid that uses localStorage to track redirection and Liquid’s {% if customer %} tag to check authentication status.
Limitation Identified: The initial solution prevented access to the account creation page, only allowing the login page.
Improved Solution: An enhanced code snippet was shared that allows visitors to access both /account/login and /account/register pages without redirection. This version uses Liquid’s {% unless %} tags to check the current URL path and only redirects when users aren’t on authentication-related pages. The code should be placed in theme.liquid above the <head> tag.
Status: The discussion appears resolved with a working implementation that balances security requirements with necessary account creation access.
Hi @Surbhi_Dudhe , I’ve tried this previously adding in the theme.liquid file but it issues in continuous reloading. I’ve find a solution and the issue is resolved.
This is the code I’ve added
{% if customer %}
{% else %}
{% endif %}
This works great, but how can we make it so that they are allowed to visit the create account page?
This solution will allow your customers/visitors to visit both the login page and the registration page, simply paste it into your theme.liquid file above .
{% comment %}
Shopify Liquid Authentication Redirect by CCC Digital
This code:
- Checks if the customer is logged in
- If not logged in, redirects to login page
- Allows access to login and registration pages without redirection
{% endcomment %}
{% unless customer %}
{% assign current_url = request.path %}
{% unless current_url contains ‘/account/login’ or current_url contains ‘/account/register’ %}
{% endunless %}
{% endunless %}