Magento 2 – Redirect to Same Page After Customer Login

By Default Magento 2 redirects to the account dashboard page after a customer logs in. This may not be very convenient for the customers as they may loose the page which they were browsing before logging in. But Magento 2 provides a very easy way to avoid this situation. If you want to keep customers on the same page after logging in, you need to change the following setting in admin panel.

Magento 2 - Redirect to same page after customer login
Magento 2 – Redirect to same page after customer login

1. Go to Admin -> Stores -> Settings -> Configuration -> Customers -> Customer Configuration
2. Now in the Login Options section change the Redirect Customer to Account Dashboard after Logging in settings to ‘No’
3. Clear the cache

This should be enough.

Redirect Using Custom Code

If you are building a custom module and want to keep customer on your module page after logging in, you can do so by this simple code. You just need to add referer parameter to the customer login url. The value of referer is the base_64 encoded hash of the redirect URL. Here is the sample code to achieve this:

namespace <namespace>\<Module>\Controller;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\UrlInterface;

class Index extends Action
    protected $urlInterface;

     * @param Context     $context
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
    public function __construct(
        Context $context,
        UrlInterface $urlInterface
    ) {
        $this->context = $context;
        $this->resultFactory = $context->getResultFactory();
        $this->urlInterface = $urlInterface;


    public function execute()
        // Get referer url
        $url = $this->_redirect->getRefererUrl();

        // Or get any custom url
        //$url = $this->urlInterface->getUrl('my/custom/url');

        // Create login URL
        $login_url = $this->urlInterface
                                array('referer' => base64_encode($url))

        // Redirect to login URL
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        return $resultRedirect;

Now after login, the customer will be redirected to the referer url instead of account dashboard page.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.