Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Redirecting in AstroJS+Svelte SSR applicaton is not working

$
0
0

I have an AstroJS SSR app with a Svelte integration. I'm creating a user signup form in Svelte which I submit to an Astro API endpoint to sign up a user. Since the form is POSTed, I want to redirect to another page once the signup is complete. However, even though Astro says it did the redirect, my application stays on the same page. I need help figuring out why.

Here's my Astro page, defined in src/pages/signup.astro:

---import MainLayout from '@/layouts/Main.astro';import SignupForm from "@/components/auth/SignupForm.svelte";---<MainLayout><SignupForm client:load /></MainLayout>

This creates the form, which is defined in src/components/SignupForm.svelte:

<script>    import * as yup from "yup";    let email = null;    let password = null;    let errors = {};    function validate()    {        const schema = yup.object().shape({            email: yup.                string().                required("We need your email to sign you up").                email("Your email must be of the form <b>name@example.com</b>"),            password: yup.                string().                required("We need a password to sign you up").                min(8, "Your password must be at least 8 characters long")        });        try        {            errors = {};            schema.validateSync({ email, password }, { abortEarly: false });            return true;        }        catch (e)        {            e.inner.forEach(error => {                errors[error.path] = error.message;            });            return false;        }    }    async function onSubmit(e)    {        if (!validate())        {            return;        }        const form = new FormData(e.currentTarget);        const response = await fetch("/api/signup", {            method: "POST",            body: form,        });        const json = await response.json();        console.log(`in svelte form response: ${JSON.stringify(json)}`);    }</script><div class="flex flex-col items-center m-4"><form class="p-8 border border-gray-400 max-w-lg lg:w-1/3 rounded-lg bg-gray-200" novalidate on:submit|preventDefault={onSubmit}><div class="my-4"><label for="email" class="mb-2 block text-sm font-bold">Email</label><input                type="email"                name="email"                placeholder="name@example.com"                class="w-full shadow appearance-none border rounded p-3"                bind:value={email}>            {#if errors.email}<p class="my-2 text-sm text-red-500">{@html errors.email}</p>            {/if}</div><div class="my-4"><label for="password" class="mb-2 block text-sm font-bold text-gray-700">Password</label><input                type="password"                name="password"                placeholder="shhh . . . don't tell anyone"                class="w-full shadow appearance-none border rounded p-3"                bind:value={password}>            {#if errors.password}<p class="my-2 text-sm text-red-500">{errors.password}</p>            {/if}</div><div class="my-4"><button class="mt-4 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Signup</button></div></form></div>

Submitting this form does client-side validation and, if that goes well, POSTs the form to the signup API at src/pages/api/signup.js:

import Auth from "@/services/auth";export const POST = async({request, redirect}) => {    const form = await request.formData();    const email = form.get("email");    const password = form.get("password");    const response = Auth.signup(email, password);    if (response.error)    {        return new Response(            JSON.stringify(response),            { status: response.error.code }        );    }    return redirect("/");};

This code is the backend API code that calls a function to signup a user and receives a success or error response. If the response indicates success, it then redirects to the main page (ideally, this should not redirect here because this is just an API, APIs don't know anything about redirects; the redirect should be initiated by the server, but that's for another time). However -- and this is the question -- the page doesn't actually redirect to the main page. In the console, I see that Astro definitely receives the 302 and says it redirected, but the browser didn't actually go to the main page.

18:33:48 [200] /signup 4mssigning up new user with email xxxx@xxxxx.com and password ftjjkyhgktjyt21:24:08 [302] POST /api/signup 2ms21:24:09 [200] / 3ms

Here's the image of the log above

Here's my astro.config.mjs file in case anyone wants to see that:

import { defineConfig } from 'astro/config';import node from "@astrojs/node";import svelte from "@astrojs/svelte";// https://astro.build/configexport default defineConfig({  devToolbar: {    enabled: import.meta.env.DEV  },  output: "server",  adapter: node({    mode: "hybrid"  }),  integrations: [svelte()]});

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>