Next.js Discord

Discord Forum

How to redirect user using api?

Answered
Auth posted this in #help-forum
Open in Discord
i've a signup api i want to redirect user using the api not client side but server side (english isnt my native langauge so dont mind)
Answered by Res
Usage is NextResponse.redirect(url, {status: statusCode})
View full answer

36 Replies

import { conn } from '@/db/conn';
import User from '@/models/userModel';
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { SendMail } from '@/helpers/mailer';

conn();

export async function POST(request: NextRequest) {
    try {
        const reqBody = await request.json();
        const { username, email, password } = reqBody;

        console.log(reqBody);

        const user = await User.findOne({ email });

        if (user) {
            return NextResponse.json({ error: 'User already exists' }, { status: 400 });
        }

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        const newUser = new User({
            email,
            username,
            password: hashedPassword,
        });

        const savedUser = await newUser.save();
        console.log(savedUser);
        await SendMail({email, emailType: 'VERIFY', userId: savedUser._id})
        

        return NextResponse.json({ error: "User registed " }, { status: 200 });
        
    } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}



 
docs?
Example:
export default async function Profile({ params }) {
  const team = await fetchTeam(params.id)
  if (!team) {
    redirect('/login')
  }
 
  // ...
}
Since you're on an API route
You'd have to do NextResponse.redirect()
that's also a possible way
another possible way would be to use headers that point to the new location 🤷‍♂️
There are many possible ways
next/navigation's redirect is clientside, no?
so can't really be used in API routes
using the router from next/navigation is clientside, yes. But he wants serverside
hence I suggested above
yes and I said that it's a possible way
hmm nah, it seems like it's not strictly client.

Redirects
app/api/route.ts

import { redirect } from 'next/navigation'
 
export async function GET(request: Request) {
  redirect('https://nextjs.org/')
}
Didn't know
it's like using cookies. There are also multiple ways and you can also use the cookies() function there
import { conn } from '@/db/conn';
import User from '@/models/userModel';
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { redirect } from 'next/navigation';
import { SendMail } from '@/helpers/mailer';

conn();

export async function POST(request: NextRequest) {
    try {
        const reqBody = await request.json();
        const { username, email, password } = reqBody;

        console.log(reqBody);

        const user = await User.findOne({ email });

        if (user) {
            return NextResponse.json({ error: 'User already exists' }, { status: 400 });
        }

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        const newUser = new User({
            email,
            username,
            password: hashedPassword,
        });

        const savedUser = await newUser.save();
        console.log(savedUser);
        await SendMail({email, emailType: 'VERIFY', userId: savedUser._id})
        



        return NextResponse.redirect(200, '/login')
        
    } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}



 
this should work right?
can yall have a look at the repo cuz this dont seems to work https://github.com/authtbh/mimories
Please read what NextResponse.redirect expects
alright
Just hover over it
First thing is a url, not a statusCode
oh-
okie
You good now?
Usage is NextResponse.redirect(url, {status: statusCode})
Answer
yup thanks
Sweet