SAN FRANCISCO — Javier Baez’s tiebreaking single capped a four-run rally in the ninth inning, and the Chicago Cubs beat the San Francisco Giants 6-5 on Tuesday night in Game 4 to win their NL Division Series.

Chasing their first World Series title since 1908, the Cubs will open the NL Championship Series at home Saturday against the Los Angeles Dodgers or Washington Nationals. That matchup is tied 2-all heading into the deciding Game 5 on Thursday.

Held to two hits over eight innings by Matt Moore, the Cubs trailed 5-2 before coming back against a beleaguered bullpen that sabotaged San Francisco one last time.

Now, the Cubs are going back to their second consecutive NLCS after finally ending San Francisco’s remarkable winning streak in postseason elimination games.

Pinch-hitter Willson Contreras tied it with a two-run single with none out. Baez singled in the go-ahead run two batters later, and the Cubs capitalized on Gold Glove shortstop Brandon Crawford’s second costly error and more untimely blunders by the Giants’ once-reliable relief staff.

One day after getting tagged in the eighth inning of an eventual 6-5, 13-inning loss, Aroldis Chapman closed this one out by striking out the side in order. When he set down Brandon Belt to end it, Chapman’s teammates rushed to the mound to hug him and begin the celebration.

Now, Chicago earns another short break — and manager Joe Maddon will have his pitching staff all lined up in the NLCS because he didn’t need to go to lefty Jon Lester in Game 5.

Maddon has his confident, power-hitting Cubs on quite an October roll. They already beat All-Star Johnny Cueto and ex-Cubs pitcher Jeff Samardzija, then waited until Moore’s stellar outing was done to pounce.

The team with baseball’s best regular-season record at 103-58 took a step closer to ending its 108-year title drought.

Chicago was swept by the New York Mets in a four-game NLCS last year.

Downright unflappable for years in these pressure-packed scenarios, the Giants had won 10 straight games when facing postseason elimination. The World Series champions in 2010, ’12 and ’14, their every-other-year title chance is over in ’16 with the club’s first postseason series defeat in the last 12.

Moore struck out 10 in eight innings.

After Cubs starter John Lackey’s night was done, Hector Rondon pitched the eighth for the win.