customer session does not work except customer page - Magento 2

To have access to real data in Magento 2 session you have to apply one of the following

  • Do it on non-cacheable page.
  • Disable full page cache.
  • Set $this->$_isScopePrivate = true for block where you are trying to access session.

Why:

Magento 2 is rendering public and private content for cacheable pages separately.

During cacheable page rendering Magento is cleaning all data that can be specific to a particular user (unsetting private data). Then separate ajax request is performed to load all private information and update blocks.

That's why session is empty during rendering.

The responsibility of cleaning private data lies on several depersonalization plugins. Customer session for example is cleaned by \Magento\Customer\Model\Layout\DepersonalizePlugin.

You can see conditions in which depersonalization will apply in \Magento\PageCache\Model\DepersonalizeChecker::checkIfDepersonalize

What are cacheable/non-cacheable pages:

In short words, cacheable page is any page that does not include non-cacheable blocks (blocks with cacheable="false" attribute in layout declaration). Correspondingly, pages with non-cacheable blocks are non-cacheable. :)

Here you can find the actual check: \Magento\Framework\View\Layout::isCacheable

Cacheable page examples: Category, Product view pages, CMS pages

Non-cacheable page examples: Customer account and checkotu pages

There is a more detailed Magento 2 Caching Overview by Alan Kent