This paper reports the measurement of J / ψ meson production in proton–proton (p p) and proton–lead (p Pb) collisions at a center-of-mass energy per nucleon pair of 5.02TeV by the CMS experiment at the LHC. The data samples used in the analysis correspond to integrated luminosities of 28pb-1 and 35nb-1 for p p and p Pb collisions, respectively. Prompt and nonprompt J / ψ mesons, the latter produced in the decay of B hadrons, are measured in their dimuon decay channels. Differential cross sections are measured in the transverse momentum range of 2<pT<30GeV/c, and center-of-mass rapidity ranges of | yCM| < 2.4 (p p) and - 2.87 < yCM< 1.93 (p Pb). The nuclear modification factor, Rp Pb, is measured as a function of both pT and yCM. Small modifications to the J / ψ cross sections are observed in p Pb relative to p p collisions. The ratio of J / ψ production cross sections in p -going and Pb-going directions, RFB, studied as functions of pT and yCM, shows a significant decrease for increasing transverse energy deposited at large pseudorapidities. These results, which cover a wide kinematic range, provide new insight on the role of cold nuclear matter effects on prompt and nonprompt J / ψ production.