Currently I'm working on my project and I started creating NestJS backend. And I use Sessions there. On the frontend part I use NextjS 13. For authentication decided to use Next-Auth. The problem with NextAuth as I understood is that the code is executed on server side, that's why cookie is not set in browser when I log in. So I have to set cookies manually inside CredentialsProvider of NextAuth. But cookie generated by Nestjs has '%' in it and when I set it, in browser I can see % was converted to %25. It's connected somehow with url encoding. How can I solve the problem and avoid converting '%'? Why does it happen? How would you realize the frontend next app if used your custom nestjs backend (Maybe wouldn't use NextAuth in this case or would set cookie in another way)? Current code for next-auth options:
import type { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import investorService from '@/axios/investor';
import NextAuth from 'next-auth';
import { NextApiRequest, NextApiResponse } from 'next';
import { cookies } from 'next/headers';
const nextAuthOptions = (
req: NextApiRequest,
res: NextApiResponse,
): NextAuthOptions => {
return {
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
email: {
label: 'Email:',
type: 'email',
placeholder: 'Введите email',
},
password: {
label: 'password:',
type: 'password',
placeholder: 'Напечатайте пароль',
},
},
async authorize(credentials) {
if (!credentials) return null;
try {
const response = await investorService.auth.login(credentials);
const sessionIdCookie: string = (
response.headers['set-cookie'] as string[]
)
.find((cookie) => cookie.includes('connect.sid'))
?.match(new RegExp(`^${'connect.sid'}=(.+?);`))?.[1]!;
cookies().set({
name: 'connect.sid',
value: sessionIdCookie,
httpOnly: true,
// secure: true,
});
return response.data;
} catch (e) {
return null;
}
},
}),
],
};
};
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return await NextAuth(req, res, nextAuthOptions(req, res));
};
export default handler;