A method includes forming a memory element on a first metal layer. A first cap layer is formed on the first metal layer and sidewalls of the memory element. A first dielectric layer is formed on the first cap layer and a portion of the cap layer on sidewalls of the memory element. A second metal layer is formed on the first dielectric layer. A portion of the memory element is removed and forms an opening. A second cap layer is formed on the top surface of the second metal layer. A second dielectric layer is deposited on the second cap layer and filling the opening. A via is etched in the second dielectric layer exposing a top surface of the memory element. A third metal layer is deposited on the second dielectric layer and filling the via.