#implement redirect on form submit in server actions

1 messages · Page 1 of 1 (latest)

vagrant schooner
#
  const discord = new Discord(env.clientId, env.clientSecret, env.redirectUri);
  const state = generateState();

  const url = await discord.createAuthorizationURL(state, {
    scopes: ["identify"],
  });


  return new Response(null, {
        status: 302,
        headers: {
            Location: url.toString(),
            "Set-Cookie": serializeCookie("discord_oauth_state", state, {
                httpOnly: true,
                secure: process.env.NODE_ENV === "production", // set `Secure` flag in HTTPS
                maxAge: 60 * 10, // 10 minutes
                path: "/"
            })
        }
    });
};
import { Button } from "@mantine/core";
import { discordSignin } from "./actions";

export function DiscordOAuth() {
  return (
    <form action={discordSignin}>
      <Button type="submit">Sign in with Discord</Button>
    </form>
  );
}

how do i use server actions to perform a redirect while setting headers?

dense sigilBOT
#

Hi @vagrant schooner. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, you can use the redirect() function from the next/navigation module to perform a redirect in server actions. However, the redirect() function does not allow you to set headers directly.

Here is an example of how to use the redirect() function in a server action:

import { redirect } from 'next/navigation'
 
export async function GET(request: Request) {
 redirect('<https://nextjs.org/'>)
}

(Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/routing/route-handlers#redirects))

In your case, you might need to modify your discordSignin function to use the redirect() function instead of returning a Response object with a Location header. However, this would not allow you to set the Set-Cookie header as you are currently doing.

Unfortunately, based on the provided knowledge sources, there is no direct way to perform a redirect while setting headers in server actions in Next.js. You might need to find a workaround or use a different approach to achieve your goal.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@vagrant schooner kapa.ai is still learning and improving, please let us know how it did by reacting below

vagrant schooner
#

@dense sigil i have a route.ts file which contains a function GET. it returns NextResponse.redirect(...) but when i visit that route, no redirection occurs and it just 404s

dense sigilBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the knowledge sources provided, there could be several reasons why your GET function in route.ts is not redirecting as expected:

  1. File Structure: The structure of your files and directories could be causing the issue. According to a Github issue comment (https://github.com/vercel/next.js/issues/52427), the route.ts file should not be at the same route segment level as page.js. If you have a structure like this:
app/
  login/
    route.ts
    page.tsx

It won't work. Instead, you should have a structure like this:

app/
  login/
    api/
      route.ts
    page.tsx

Or this:

app/
  login/
    route.ts
  1. Return Type: The GET function in route.ts should return a Response object or a Promise that resolves to a Response object. If you're using the redirect() function from next/navigation, it might not be returning the correct type. According to a Github issue (https://github.com/vercel/next.js/issues/55623), you might need to specify Promise<never> as the return type of your GET function:
export async function GET(request: Request): Promise<never> {
  redirect('<https://nextjs.org/'>)
}
  1. Static Exports: If you're using static exports with next build, only the GET HTTP verb is supported and it will render a static response. If you need to read dynamic values from the incoming request, you cannot use a static export (Next.js Docs (https://nextjs.org/docs/app/building-your-application/deploying/static-exports#route-handlers)).
#

If none of these solutions work, there might be an issue with your specific setup or code. You might want to check the official Next.js documentation or ask for help in the Next.js community.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@vagrant schooner kapa.ai is still learning and improving, please let us know how it did by reacting below

vagrant schooner
#

@dense sigil how do i call this nextjs api route?

dense sigilBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To call a Next.js API route, you can use the fetch() function in JavaScript. The URL of the API route will be the path to the file inside the pages/api directory.

For example, if you have an API route defined in pages/api/hello.ts, you can call it like this:

fetch('/api/hello')
  .then(response => response.json())
  .then(data => console.log(data));

This will send a GET request to the /api/hello endpoint and log the response data to the console.

If you need to send a POST request or include additional options, you can pass them as the second argument to fetch(). For example:

fetch('/api/hello', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    key: 'value',
  }),
})
  .then(response => response.json())
  .then(data => console.log(data));

This will send a POST request with a JSON payload to the /api/hello endpoint.

Remember that these API routes are server-side only and won't increase your client-side bundle size. Any file inside the pages/api folder is treated as an API endpoint instead of a page (Next.js Docs (https://nextjs.org/docs/pages/building-your-application/routing/api-routes)).

Also, if you're calling the API route from a client component, you can use useEffect or a data fetching library like swr (Github Issue Comment (https://github.com/vercel/next.js/issues/58952)).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@vagrant schooner kapa.ai is still learning and improving, please let us know how it did by reacting below

vagrant schooner
#

@dense sigil export const dynamic = 'force-dynamic' // defaults to auto
export async function GET(request: Request) {
return Response.json("Hello world!", { status: 200 });
}

still returns 404

dense sigilBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the provided knowledge sources, it seems like there might be an issue with the way your route handler is set up or how you're trying to access it.

Here are a few things you could check:

  1. File Structure: Make sure your route.ts file is in the correct location. It should be inside the pages/api directory or a subdirectory of pages/api. The URL of the API route corresponds to the file path relative to the pages/api directory.

  2. File Name: Ensure that the file name of your route handler matches the URL you're trying to access. For example, if your file is named hello.ts, you should be able to access it at /api/hello.

  3. Function Export: Make sure you're exporting your GET function correctly. It should be a default export or named export from the route.ts file.

  4. Server Running: Ensure that your Next.js server is running when you're trying to access the API route. If you're running a development server, it should be accessible at <http://localhost:3000/api/your-route.>

If none of these solutions work, there might be an issue with your specific setup or code. You might want to check the official Next.js documentation or ask for help in the Next.js community.

Unfortunately, without more specific information about your setup and the exact error message you're seeing, it's difficult to provide a more precise answer.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

vagrant schooner
#

@dense sigil this is next 14 using app router

dense sigilBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js 14 with the App Router, the routing system works a bit differently compared to the traditional pages/api routing. The App Router introduces a new directory named app which works alongside the pages directory.

The GET function you're trying to define seems to be a route handler. In the App Router, route handlers are defined in a route.ts file inside the app directory or a subdirectory of app. The URL of the route corresponds to the file path relative to the app directory.

Here's an example of how you might define a route handler in app/hello/route.ts:

export async function GET(request: Request) {
  return new Response(JSON.stringify({ message: "Hello world!" }), { status: 200 });
}

You should then be able to access this route at /app/hello.

Please note that the App Router takes priority over the Pages Router. Routes across directories should not resolve to the same URL path and will cause a build-time error to prevent a conflict (Next.js Docs (https://nextjs.org/docs/app/building-your-application/routing#the-app-router)).

If you're still getting a 404 error, there might be an issue with your specific setup or code. You might want to check the official Next.js documentation or ask for help in the Next.js community.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: