Expresses going/coming somewhere for the purpose of doing an action. The verb stem (or action noun) before に is the purpose of the movement: 'go to do X'.
[Verb masu-stem / action noun] + に行く / に来る / に帰る
スーパーに野菜を買いに行きました。
Suupaa ni yasai o kai ni ikimashita.
I went to the supermarket to buy vegetables.
買い (buy, masu-stem) + に行く (go in order to ~)
彼が家へ遊びに来た。
Kare ga ie e asobi ni kita.
He came over to my house to hang out.
遊び (play/hang out, masu-stem) + に来た (came in order to ~)
夏休みに海へ泳ぎに行く。
Natsuyasumi ni umi e oyogi ni iku.
I'm going to the sea to swim during summer vacation.
泳ぎ (swim, masu-stem) + に行く (go in order to ~)
• Action nouns (買い物 shopping, 勉強 study, 食事 a meal) attach directly without turning into a verb: 買い物に行く (go shopping). You drop the する. • The movement verb is usually 行く, 来る, or 帰る.
The JLPT rarely asks whether you recognise a pattern — it asks which of several similar patterns fits. These are the ones に行く is tested against.
ために (for the purpose of) works with any verb and any main clause; に行く specifically attaches a purpose to a verb of motion (go/come/return).
Study Japanese grammar on LenGaki

Get the Android app
The app adds offline study, home-screen widgets, stroke-order tracing, speaking practice with pronunciation scoring, and an AI tutor that answers questions in context — none of which fits in a browser tab.