Next.js Discord

Discord Forum

Using Next.js 14 Redirect with Hidden Directories and Server Actions for Different Layouts

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
Context: I'm utilizing Next.js 14 for a project with a specific structure involving hidden directories and server actions, and I'm encountering challenges with redirection.

Project Structure:

Two hidden directories: home and form within the app folder.
Each directory has its distinct layout.
The root page is in home/page.tsx.

Issue:

I need to redirect from a file in the form directory to the root page.
The redirection is to be triggered through a server action in (form)/form/action.tsx, which is then invoked in (form)/form/page.tsx.
When I use redirect("/") in this setup, it doesn't function as expected.
It works only if the file is placed in (home)/form/page.tsx, but this approach disrupts the layout design.

Requirement:

How to correctly implement the redirect from (form)/form/page.tsx to the root page using server actions without affecting the separate layouts in the hidden directories?
Can redirect be effectively used across hidden directories in this setup?

Example with Server Action:

"use server"
// In (form)/form/action.tsx
import { redirect } from 'next/navigation'

export async function serverAction() {
  // Action logic
  if (condition) {
    redirect('/')  //should redirect to @/(home)/page
  }
}

// In (form)/form/page.tsx
import { serverAction } from '@/(form)/form/action'

// Usage of serverAction within page component logic

Specific Questions:

Is there a specific approach or development strategy to ensure redirect works across hidden directories while maintaining individual layouts, or is it best to have just app/page.tsx with (form) folder leaving out the (home) folder?
Are there best practices in structuring the project to facilitate such redirections using server actions?

0 Replies