Well spotted! This is very common. Bach often uses a brief modulation to the subdominant key near the end of his fugues, preludes and inventions (presumably other pieces, too). Sometimes this is so brief, that we feel like we are just travelling through this key, without really modulating to it. Sometimes this is over a final tonic pedal, which is really “bringing the harmony home”, although not in your examples.
The reason he does this, is related to how much of Western common practice music is harmonically structured. Although we may modulate to a wide range of related keys, by far the most commonly used structural modulations are basically an arch: Tonic -> Dominant -> Tonic (again). If we imagine this as a “swing” one place to the sharp side around the circle of fifths and then back again, the move to the subdominant helps to “balance” this, by swinging “a bit too far” to the flat side, as we return to the tonic, with the final settling on the tonic feeling even more like a resolution as a result.
Another way to think about the same structural harmonic movement, is considering the brightness of related keys. As we move to sharper keys around the circle of fifths they sound comparatively brighter; as we move to flatter keys they sounds comparatively darker. [Thanks to Tim for commenting on this, hence the edit for clarity...] We start at the tonic, our home key, move to a brighter key, the dominant, and then back to our home key. To emphasise this movement back from a brighter key to our home key, we go "a bit darker" than our home key before finally settling there.
We could come up with numerous analogies for this kind of movement: tuning a sharp guitar string down below the note we want, before coming back up to pitch; taking a clipping recorded volume down below the volume we want before gradually raising it to the optimum position etc.