Depends on your attacker's units. I usually in defending against an assault set up a bubble in front of the gate the attacker comes from. This looks kind of like

XXXXGGXXXX
----P---P----
------P------
----S---S----

Where P are spears and S are swords. Sometimes the S can be spears too, depending on your force.
If you got javelin infantry (not cavalry as those friendly fire too often), place em behind the bubble or on the walls (except if the enemy takes your walls using ladders/towers)

This way the enemy is limited in the number of troops he can send through and a lot of crowding prevents his troops from getting through effectively due to a few laggers holding them back. This also allows you to assault the enemy from both flanks and the front and is fairly airtight (move in second row if your first row dies too quickly) It is detrimental to enemy morale and also stops significant hoardes of cav getting in at all. Just make sure your general is nearby to boost your morale or the enemy by sheer weight of numbers will kill your morale.

If your enemy is mainly having sword or halberd units, you probably don't want to try holding him at the gates but crowd all your units in the townsquare. Why? Because they NEVER rout in the square and your enemy has to take it.