Clustered regularly interspaced short palindromic repeats (CRISPR)-Cas systems provide protection against viral and plasmid infection by capturing short DNA sequences from these invaders and integrating them into the CRISPR locus of the prokaryotic host. These sequences, known as spacers, are transcribed into short CRISPR RNA guides that specify the cleavage site of Cas nucleases in the genome of the invader. It is not known when spacer sequences are acquired during viral infection. Here, to investigate this, we tracked spacer acquisition in Staphylococcus aureus cells 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 the cos site, 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.