How to create server component for file streaming or redirection in nextJS app router?

This is how I tried to create a kind of redirection service in my nextJS application.
There are two options: The content of a file on my server will be streamed or there is a simple link and the user is directly redirected.

This is done in page router.

Now I would like to migrate this to the app router. But there is no getServerSideProps in the app router anymore. Instead there are server compontents.

pages/[hash].tsx

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { GridFSBucket, GridFSFile, MongoServerError, ObjectId } from 'mongodb'
import { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
export const getServerSideProps: GetServerSideProps = async ({
res,
req,
query: { hash }
}) => {
if (!hash) return { notFound: true }
try {
const database = await mongodb()
const Data = database.collection('data')
const { fileId, link } = (await Data.findOne({ uid: hash })) || {}
if (fileId) {
const bucket = new GridFSBucket(database)
const id = new ObjectId(fileId)
const files: GridFSFile[] = await bucket.find({ _id: id }).toArray()
const file = files[0]
const { contentType } = file
// Send header
const header = { 'Content-Type': contentType }
let status = 200
res.writeHead(status, header)
// Stream data
bucket
.openDownloadStream(id, options)
.on('data', (chunk) => {
res.write(chunk)
})
.on('end', () => {
res.end()
})
.on('error', (err) => {
throw err
})
} else if (link) {
return {
redirect: {
destination: link,
permanent: false
}
}
}
return {
props: {}
}
} catch (error) {
if (error instanceof MongoServerError) {
console.error(error)
}
throw error
}
}
const HashPage: NextPage = () => {
return (
<>
<Head>
<title>Redirection</title>
</Head>
<div>Error: Content doesn't exist</div>
</>
)
}
export default HashPage
</code>
<code>import { GridFSBucket, GridFSFile, MongoServerError, ObjectId } from 'mongodb' import { GetServerSideProps, NextPage } from 'next' import Head from 'next/head' export const getServerSideProps: GetServerSideProps = async ({ res, req, query: { hash } }) => { if (!hash) return { notFound: true } try { const database = await mongodb() const Data = database.collection('data') const { fileId, link } = (await Data.findOne({ uid: hash })) || {} if (fileId) { const bucket = new GridFSBucket(database) const id = new ObjectId(fileId) const files: GridFSFile[] = await bucket.find({ _id: id }).toArray() const file = files[0] const { contentType } = file // Send header const header = { 'Content-Type': contentType } let status = 200 res.writeHead(status, header) // Stream data bucket .openDownloadStream(id, options) .on('data', (chunk) => { res.write(chunk) }) .on('end', () => { res.end() }) .on('error', (err) => { throw err }) } else if (link) { return { redirect: { destination: link, permanent: false } } } return { props: {} } } catch (error) { if (error instanceof MongoServerError) { console.error(error) } throw error } } const HashPage: NextPage = () => { return ( <> <Head> <title>Redirection</title> </Head> <div>Error: Content doesn't exist</div> </> ) } export default HashPage </code>
import { GridFSBucket, GridFSFile, MongoServerError, ObjectId } from 'mongodb'
import { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'

export const getServerSideProps: GetServerSideProps = async ({
  res,
  req,
  query: { hash }
}) => {
  if (!hash) return { notFound: true }

  try {
    const database = await mongodb()
    const Data = database.collection('data')
    const { fileId, link } = (await Data.findOne({ uid: hash })) || {}

    if (fileId) {
      const bucket = new GridFSBucket(database)
      const id = new ObjectId(fileId)
      const files: GridFSFile[] = await bucket.find({ _id: id }).toArray()
      const file = files[0]
      const { contentType } = file

      // Send header
      const header = { 'Content-Type': contentType }
      let status = 200
      res.writeHead(status, header)

      // Stream data
      bucket
        .openDownloadStream(id, options)
        .on('data', (chunk) => {
          res.write(chunk)
        })
        .on('end', () => {
          res.end()
        })
        .on('error', (err) => {
          throw err
        })
    } else if (link) {
      return {
        redirect: {
          destination: link,
          permanent: false
        }
      }
    }

    return {
      props: {}
    }
  } catch (error) {
    if (error instanceof MongoServerError) {
      console.error(error)
    }
    throw error
  }
}

const HashPage: NextPage = () => {
  return (
    <>
      <Head>
        <title>Redirection</title>
      </Head>
      <div>Error: Content doesn't exist</div>
    </>
  )
}

export default HashPage

In my case header are send and some content is streamed or there is a direct redirection. How do I do this correctly in nextJS? Maybe this content has to be moved to an api folder? Do I need a middleware?
Or maybe moved to app/[hash]/page.tsx? But in this case I don’t know where to get res, req, query: { hash } from and how to handle to show an error component in case of an error.

app/[hash]/page.tsx

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const HashPage: NextPage = async () => {
await getServerSideProps() // <- missing props here
return (
<div>Error: Content doesn't exist</div>
)
}
export default HashPage
</code>
<code>const HashPage: NextPage = async () => { await getServerSideProps() // <- missing props here return ( <div>Error: Content doesn't exist</div> ) } export default HashPage </code>
const HashPage: NextPage = async () => {
  await getServerSideProps() // <- missing props here

  return (
    <div>Error: Content doesn't exist</div>
  )
}

export default HashPage

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật