Localized interactions are predicted to favour the evolution of cooperation amongst individuals within a population. One important factor that can localize interactions is habitat patchiness. We hypothesize that habitats with greater patchiness (greater edge-to-area ratio) can facilitate the maintenance of cooperation. This outcome is believed to be particularly relevant in pathogenic microbes that can inhabit patchy habitats such as the human respiratory tract. To test this hypothesis in a simple but spatially controlled setting, we designed a transparent microhabitat chip (MHC) with multiple patchiness treatments at the 100 micron scale. The MHC is a closed system that sustains bacterial replication and survival for up to 18 hours, and allows spatial patterns and eco-evolutionary dynamics to be observed undisturbed. Using the opportunistic pathogen Pseudomonas aeruginosa, we tracked the growth of wild-type cooperators, which produce the public good pyoverdin, in competition with mutant defectors or cheaters that use, but do not produce, pyoverdin. We found that while defectors on average outperformed cooperators in all habitats, habitat patchiness significantly alleviated the ecological pressure against cooperation due to defection, leading to coexistence. Our results confirmed that habitat-level spatial heterogeneity can be important for cooperation. The MHC enables novel experiments, allows multiple parameters to be precisely varied and studied simultaneously, and will help uncover dynamical features of spatial ecology and the evolution of pathogens.