So ive been using res.cookie() to send the user's token to the frontend for a while, however, i've only ever tested it locally. I recently wanted to host my mern stack app on render.com and it turns out that i can't use res.cookie() to send the token to the frontend because cookies dont set within sub domains, which is what render.com gives you i.e "website-name.render.com". I would have to buy a custom domain name which i cant afford yet. This is what i mean
Sending the token to the frontend using res.cookie:
const register = async (req, res) => {
const user = await User.create({...req.body})
const token = user.createJWT()
res.status(StatusCodes.CREATED).cookie('token', token).json({ name: user.name})
}
Getting the token using an auth middleware:
const authMiddleware = async (req, res, next) => {
const {token} = req.cookies
if(token){
try{
const {userId, name} = jwt.verify(token, process.env.JWT_SECRET)
req.user = {userId, name}
next()
}
catch(error){
throw new UnauthenticatedError('Authentication invalid')
}
}else{
throw new UnauthenticatedError('no token')
}
}
Essentially, this code above, which works fine locally, doesnt work when i host it on render.com, I am currently getting the "no token" error. Which brings me to my question, if i cant use cookies, whats my alternative here or am i forced to pay for a custom domain even though this is a personal project?