Clustered regularly interspaced short palindromic repeats (CRISPR)–Cas systems provide protection against viral1and plasmid2infection by capturing short DNA sequences from these invaders and integrating them into the CRISPR locus of the prokaryotic host1. These sequences, known as spacers, are transcribed into short CRISPR RNA guides3,4,5that specify the cleavage site of Cas nucleases in the genome of the invader6,7,8. It is not known when spacer sequences are acquired during viral infection. Here, to investigate this, we tracked spacer acquisition inStaphylococcus aureuscells harbouring a type II CRISPR–Cas9 system after infection with the staphylococcal bacteriophage ø12. We found that new spacers were acquired immediately after infection preferentially from thecossite, the viral free DNA end that is first injected into the cell. Analysis of spacer acquisition after infection with mutant phages demonstrated that most spacers are acquired during DNA injection, but not during other stages of the viral cycle that produce free DNA ends, such as DNA replication or packaging. Finally, we showed that spacers acquired from early-injected genomic regions, which direct Cas9 cleavage of the viral DNA immediately after infection, provide better immunity than spacers acquired from late-injected regions. Our results reveal that CRISPR–Cas systems exploit the phage life cycle to generate a pattern of spacer acquisition that ensures a successful CRISPR immune response.