In this paper, we propose a protocol to realize nonadiabatic geometric quantum computation (NGQC)of W-state codes in a spin system using invariant-based reverse engineering. The Heisenberg XY interaction of spin qubits provides a two-dimensional computational subspace spanned by a pair of W states. By applying a time-dependent magnetic on the spin qubits, we realize the effective Pauli operations for the computational subspace. Assisted by the invariant-based reverse engineering, the waveform of the control field is designed and the evolution paths for the NGQC is found. The performance of the protocol under the influence of experimental imperfections is estimated by the numerical simulations with available parameters. The results demonstrate that the protocol is robust against systematic error, random noise and decoherence. Therefore, the protocol may be promising to implement fast and robust manipulation of W states in spin systems.