Hard carbon materials with rational heteroatom doping and nanostructure are potential candidates for potassium-ion batteries (PIBs) anodes and arouse enormous interest from researchers. However, the application of hard carbon anodes still suffers from many obstacles of rapid capacity fading, low rate capability, extra procedures for introducing heteroatom doping and environmentally unfriendly template-removal process. Herein, nitrogen-doped carbon nanofoams (denoted as N-CNFs), which are fabricated through CO2 aided two-step foaming and pyrolysis of commercially available polyacrylonitrile, are demonstrated as high-performance PIBs anodes. The influences of pyrolysis temperature on the physical/chemical properties including porous structure, graphitization degree, nitrogen doping level, as well as electrochemical performances of N-CNFs are revealed by a series of material characterizations and electrochemical measurements. The as-fabricated N-CNF pyrolyzed at 750 °C exhibits the optimal electrochemical performances with a high reversible specific capacity (332 mA h g−1 at 0.1 A g−1 over 100 cycles), excellent rate capability (144 mA h g−1 at 5 A g−1) and great cyclability (195 mA h g−1 at 1 A g−1 over 2000 cycles). The appealing electrochemical performances benefit from the collaborative contribution of moderate specific surface area, graphitization degree and nitrogen doping level. The results could provide some guidelines for designing nitrogen-doped carbon nanofoams as high-performance anodes for PIBs.