Next.js Discord

Discord Forum

How to redirect a user in a server side action

Answered
Shiba Inu posted this in #help-forum
Open in Discord
Shiba InuOP
As the name implies, I've made a server side action and I want to redirect the user after completing the action. I can return the id then redirect on the component but I was wondering if I was able to do it within the action itself:

'use server'
import { db } from "~/app/_lib/db"
import { currentUser } from "@clerk/nextjs/server";

export default async function createBot(formData: FormData) {
    const user = await currentUser()
    if (!user) {
        console.error('Not authenticated')
        return { error: 'Not authenticated' }
    }
    
    db.bot.create({
        data: {
            ownerId: user.id,
            botToken: formData.get('bot-token') as string,
            name: 'test'
        }
    }).then((bot) => {
        console.log(`Bot created: ${bot.id}`)
        // redirect to bot page        
    }).catch((error) => {
        console.error(`Error creating bot: ${error}`)
    })
}
Answered by Allegheny mound ant
const botId = await db.bot.create({
data: {
ownerId: user.id,
botToken: formData.get('bot-token') as string,
name: 'test'
}
}).then((bot) => {
console.log(Bot created: ${bot.id})
return bot.id
}).catch((error) => {
console.error(Error creating bot: ${error})
});

redirect(/url-to-bot/?bot=${botId})
View full answer

15 Replies

Allegheny mound ant
import { redirect } from 'next/navigation';

once you done with your action, you can simply call
redirect('diresired-path');
Shiba InuOP
ah I tried that but I got Error creating bot: Error: NEXT_REDIRECT

I just took it out of my try accept and it work though
idk why but heck if it works it works
now I just need to get bot id in scope :p
Allegheny mound ant
have you consired passing the id as query param?
could simplify your redirection
Shiba InuOP
im going to be generating the id with the prisma create function so I dont think that would work
thanks for the suggestion tho
Allegheny mound ant
const botId = await db.bot.create({
data: {
ownerId: user.id,
botToken: formData.get('bot-token') as string,
name: 'test'
}
}).then((bot) => {
console.log(Bot created: ${bot.id})
return bot.id
}).catch((error) => {
console.error(Error creating bot: ${error})
});

redirect(/url-to-bot/?bot=${botId})
Answer
Shiba InuOP
ah thanks that is way cleaner than what id done lol.
ay it works, you're the best ty 🏆
Allegheny mound ant
make sure you validate the response before sending it to the query otherwise you might end up with ?bot=undefined or something like that
Shiba InuOP
good shout
@Shiba Inu idk why but heck if it works it works
American
It's because the redirect throws an error which nextjs then handles as a redirect. You can handle it like this:

import { isRedirectError } from "next/dist/client/components/redirect";

if (isRedirectError(error)) {
  throw error;
}