Cannot redirect in Next.js 13 using res.redirect()

40 Views Asked by At

I'm trying to set nickname and profile image and then if it's works fine, request the backend to try and authorize/redirect to home.

/init/page.tsx in next

    const submitAvatar = async () => {
        const formData = new FormData(); 
        if (!avatarFile) {
            alert('You are using default avatar');
        }
        else {
            formData.append('avatar', avatarFile);
        }

        try {
            const response = await fetch('http://localhost:3001/user/photo', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${value}`,
                },
                body: formData,
            });
            try {
                if (response.ok) {
                    await fetch('http://localhost:3001/auth/init', { //request redirect here
                        method: 'GET',
                        headers: {
                            'Authorization': `Bearer ${value}`,
                        },
                    })
                }
            } catch (error) {
                console.error('redirect', error);
            }
        } catch (error) {
            console.error(error);
        }
    };


  @Get('init')
  @UseGuards(InitAuthGuard)
  async getInit(
    @GetUser() user: UserEntity,
    @Res() res: Response
  ){
    const {Token} = await this.authService.existingSign(user.uid);
    
    res.cookie('Token', Token);
    res.redirect('http://localhost:3000');
  }

At first, this got a CORS error

so I add the CORS config on config.next.js

/** @type {import('next').NextConfig} */

const nextConfig = {
    async headers() {
        return [
            {
                source: '/(.*)', // Match all paths
                headers: [
                    {
                        key: 'Access-Control-Allow-Origin',
                        value: '*', // Adjust this based on your needs
                    },
                    {
                        key: 'Access-Control-Allow-Credentials',
                        value: 'true',
                    },
                    {
                        key: 'Access-Control-Allow-Headers',
                        value: 'Authorization', // Include any other headers you need
                    },
                ],
            },
        ];
    }
}

module.exports = nextConfig

this resolves the CORS error. but still it doesn't redirect. anyone know why? I'm guessing it because the next supports SPA and the redirect results in refreshing.. so it won't work.

0

There are 0 best solutions below