Next.js Discord

Discord Forum

How can I redirect a user to the previous page after a successful login with Next?

Unanswered
Jacquit posted this in #help-forum
Open in Discord
If a user goes to the "/dashboard" page while being logged out we want to redirect him/her to login page. But I want to add redirect so that after successful login, the user is automatically redirected to the "/dashboard" page.
Can anyone help me achieve this, please?
This is my code on the login page:

const Login = () => {
const router = useRouter();
const { t } = useTranslation('login');
const [logIn] = userAuthStore((set) => [set.logIn]);

const mutation = useMutation<PostLoginResponse, AxiosError<PostLoginError>, PostLoginPayload>(
(payload) => postLogin(payload),
{
onSuccess: (data) => {
logIn(data.access);
redirect(router, '/dashboard');
},
onError: (error) => {
if (error.response?.status === 401) {
formik.setFieldError('password', t('unauthorized'));
}

error.response?.data.errors
.filter((e) => ['email', 'password'].indexOf(e.fieldName) > -1)
.forEach((e) => {
formik.setFieldError(e.fieldName, t(${e.msg}));
});
},
}
);

const formik = useFormik({
initialValues: {
email: '',
password: '',
},
validationSchema: Yup.object({
email: Yup.string().trim().email(t('email-invalid')).required(t('email-required')),
password: Yup.string()
.required(t('password-required'))
.min(4, t('password-min-length', { min: 4 })),
}),
onSubmit: (values) => {
mutation.mutate(values);
},
});

};

export default Login;

11 Replies

Alaska pollock
why are you using useRouter?
All you need to do is import "import { redirect } from 'next/navigation'", then you can use redirect('whatever-route-path-you-want)
Thanks for the quick answer.
Yes, I have used useRouter, but my problem is how to get to the previous path. How can I store it and use it during the login process? Do you have any ideas about this?
Alaska pollock
yes, just use redirect('..');
that will redirect the user to the previous path, but i'm not sure how to store it
@Jacquit If a user goes to the "/dashboard" page while being logged out we want to redirect him/her to login page. But I want to add redirect so that after successful login, the user is automatically redirected to the "/dashboard" page. Can anyone help me achieve this, please? This is my code on the login page: const Login = () => { const router = useRouter(); const { t } = useTranslation('login'); const [logIn] = userAuthStore((set) => [set.logIn]); const mutation = useMutation<PostLoginResponse, AxiosError<PostLoginError>, PostLoginPayload>( (payload) => postLogin(payload), { onSuccess: (data) => { logIn(data.access); redirect(router, '/dashboard'); }, onError: (error) => { if (error.response?.status === 401) { formik.setFieldError('password', t('unauthorized')); } error.response?.data.errors .filter((e) => ['email', 'password'].indexOf(e.fieldName) > -1) .forEach((e) => { formik.setFieldError(e.fieldName, t(`${e.msg}`)); }); }, } ); const formik = useFormik({ initialValues: { email: '', password: '', }, validationSchema: Yup.object({ email: Yup.string().trim().email(t('email-invalid')).required(t('email-required')), password: Yup.string() .required(t('password-required')) .min(4, t('password-min-length', { min: 4 })), }), onSubmit: (values) => { mutation.mutate(values); }, }); }; export default Login;
a common practice is to redirect from /protected/path to /login?destination=/protected/path then redirect to the destination value

if no destination value is present, then redirect to a default page (e.g. /dashboard)
Do you think it's possible to store this protected path in session storage and then use it as you suggested here?
@Jacquit Do you think it's possible to store this protected path in session storage and then use it as you suggested here?
whether it is possible or not i would say possible, though i don't recommend it
because you will have to do all the useEffect boilerplate to handle this
not worth it, if just to make the URL a little bit nicer