#passing data to another page
1 messages · Page 1 of 1 (latest)
In Next.js, you can pass data from one page to another using several methods. Here are a few options:
-
Using Query Parameters: You can pass data to another page using query parameters in the URL. This is suitable for small amounts of data.
-
Using Context: If you want to share data across multiple components or pages, you can use React's Context API. This is suitable for global state like user authentication status.
-
Using a State Management Library: For more complex state management, you can use a state management library like Redux or Zustand.
-
Using Local Storage or Session Storage: You can store data in the browser's local storage or session storage and then retrieve it in the other page. This is suitable for persisting state across sessions or tabs.
Here's an example of how you can pass data from a login page to another page using fetch and Next.js's router:
import { useRouter } from 'next/router'
export default function LoginPage() {
const router = useRouter()
async function handleSubmit(event) {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const email = formData.get('email')
const password = formData.get('password')
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
})
if (response.ok) {
const data = await response.json()
// Pass data to the profile page via query parameters
router.push(`/profile?data=${encodeURIComponent(JSON.stringify(data))}`)
} else {
// Handle errors
}
}
return (
<form onSubmit={handleSubmit}>
<input type="email" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<button type="submit">Login</button>
</form>
)
}
In the profile page, you can then retrieve the data from the query parameters:
```jsx
import { useRouter } from 'next/router'
export default function ProfilePage() {
const router = useRouter()
const data = JSON.parse(decodeURIComponent(router.query.data))
// Use the data...
}
Please note that this is a simple example and may not be suitable for all use cases. For example, sensitive data should not be passed via query parameters for security reasons.
For more information, you can check the Next.js documentation on Routing (https://nextjs.org/docs/routing/introduction) and API Routes (https://nextjs.org/docs/api-routes/introduction).
Sources:
- Next.js Authentication (https://nextjs.org/docs/pages/building-your-application/authentication#implementing-authentication)
- Github Issue: How to share data from components in two different routes (https://github.com/vercel/next.js/issues/63762)